PHP code example of familysearch / fs-php-lite

1. Go to this page and download the library: Download familysearch/fs-php-lite library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

familysearch / fs-php-lite example snippets


// Integration
$fs = new FamilySearch(['environment' => 'integration']);

// Beta
$fs = new FamilySearch(['environment' => 'beta']);

// Production
$fs = new FamilySearch(['environment' => 'production']);


include_once('FamilySearch.php');

// Create the SDK instance
$fs = new FamilySearch([
  'environment' => 'beta', // 'integration', 'beta', or 'production'
  'appKey' => $_ENV['FS_APP_KEY'], // NEVER hardcode credentials - use environment variables
  'redirectUri' => 'https://example.com/fs-redirect',
  
  // Tell it to automatically save and load the access token from $_SESSION. 
  'sessions' => true, // This defaults to true
  'sessionVariable' => 'FS_ACCESS_TOKEN',
  
  // RECOMMENDED: Enable AES-256-GCM encryption for session tokens in production
  'sessionEncryption' => true,
  'sessionEncryptionKey' => $_ENV['FS_SESSION_ENCRYPTION_KEY'], // NEVER hardcode the key!
  
  // Necessary for when the developer wants to store the accessToken somewhere
  // besides $_SESSION
  'accessToken' => '',
  
  // How many times should a throttled response be retried? Defaults to 5
  'maxThrottledRetries' => 5,
  
  // Activate pending modifications
  'pendingModifications' => ['consolidate-redundant-resources', 'current-person-401'],
  
  // Modify the default user agent by appending this value
  'userAgent' => 'myApp/1.2.3',
  
  // Enable optional serialization and deserialization with objects via gedcomx-php
  'objects' => true
]);

// OAuth step 1: Redirect
$fs->oauthRedirect();

// OAuth step 2: Exchange the code for an access token.
//
// This will automatically retrieve the code from $_GET and exchange it for
// an access token. The access token is contained in the response object if the
// request was successful. The token doesn't need to be saved to a variable if
// sessions are enabled because the SDK will automatically save it.
$response = $fs->oauthResponse();

// Get the current user
$response = $fs->get('/platform/users/current');

// All response objects have the following properties
$response->statusCode;     // Integer
$response->statusText;     // String
$response->headers;        // Array
$response->effectiveUrl;   // String
$response->body;           // String
$response->requestMethod;  // String
$response->requestHeaders; // Array
$response->requestBody;    // String
$response->redirected;     // Boolean; defaults to false
$response->throttled;      // Boolean; defaults to false
$response->curl;           // A reference to the curl resource for the request

// If the response included JSON in the body then it will be parsed into an
// associative array and be available via the `data` property.
$response->data; 

// If a request is forwarded then the response will contain the original URL
$response->originalUrl;

// If a request is throttled then the response will tell how many times it was
// throttled until it finally succeeded.
$response->retries;

// You can POST too. The body may be an array or a string.
$response = $fs->post('/platform/tree/persons/PPPP-PPP', [
  'body' => $personData
]);

// The SDK defaults the Accept and Content-Type headers to application/x-fs-v1+json
// for all /platform/ URLs. But that doesn't work for some endpoints that 

$fs = new FamilySearch([
    'appKey' => $_ENV['FS_APP_KEY'],
    'environment' => 'production',
    
    // Enable session encryption (RECOMMENDED for production)
    'sessionEncryption' => true,
    'sessionEncryptionKey' => $_ENV['FS_SESSION_ENCRYPTION_KEY']
]);

$fs = new FamilySearch([
    'appKey' => $_ENV['FS_APP_KEY'],
    'sessionEncryption' => true,  // Add this line
    'sessionEncryptionKey' => $_ENV['FS_SESSION_ENCRYPTION_KEY']  // Add this line
]);

$fs = new FamilySearch([
    'appKey' => $_ENV['FS_APP_KEY'],
    'expirationWarningThreshold' => 300 // Warn 5 minutes before expiration
]);

if ($fs->isTokenExpired()) {
    // Token is expired or expiring soon - re-authenticate
    $fs->oauthPassword($username, $password);
}

$response = $fs->get('/platform/tree/persons/PPPP-PPP');

$fs = new FamilySearch([
    'appKey' => $_ENV['FS_APP_KEY'],
    'onAuthenticationFailure' => function($response, $reason) use (&$fs, $username, $password) {
        if ($reason === 'expired') {
            // Automatically re-authenticate
            $fs->oauthPassword($username, $password);
            // SDK automatically retries the original request
        }
    }
]);

// Make requests normally - re-authentication happens transparently
$response = $fs->get('/platform/tree/persons/PPPP-PPP');

// Get detailed token information
$tokenInfo = $fs->getAccessToken(true);

echo "Token expires: " . date('Y-m-d H:i:s', $tokenInfo['expires_at']) . "\n";
echo "Is expired: " . ($tokenInfo['is_expired'] ? 'Yes' : 'No') . "\n";

// Calculate time remaining
$timeRemaining = $tokenInfo['expires_at'] - time();
$minutesRemaining = floor($timeRemaining / 60);
echo "Time remaining: {$minutesRemaining} minutes\n";

$fs = new FamilySearch([
    'objects' => true
]);

$response = $fs->post('/platform/tree/persons', [
    'body' => new \Gedcomx\Extensions\FamilySearch\FamilySearchPlatform([
        'persons' => [ $personData ]
    ])
]);

$persons = $response->gedcomx->getPersons();
bash
# Generate a base64-encoded key (recommended)
php -r "echo base64_encode(random_bytes(32));"
# Output: WdaFfj4iL3Epz2o9phaBbh7FyA5fJs3lCcr6YB4QQxo=

# Or generate a hex-encoded key
php -r "echo bin2hex(random_bytes(32));"
# Output: 4c0bd859f72d55003baa72e76fea385e599c9562b1b75a1fec0831b19f04118a
bash
php -r "echo base64_encode(random_bytes(32));"
# Copy the output: WdaFfj4iL3Epz2o9phaBbh7FyA5fJs3lCcr6YB4QQxo=
bash
   sudo chmod 700 /var/lib/php/sessions