### Install Facebook SDK using Composer
Source: https://github.com/facebookarchive/php-graph-sdk/blob/5.x/docs/getting_started.md
This command installs the Facebook SDK for PHP using Composer, the recommended package manager for PHP. It adds the SDK as a dependency to your project.
```bash
composer require facebook/graph-sdk
```
--------------------------------
### Manually Include SDK Autoloader
Source: https://github.com/facebookarchive/php-graph-sdk/blob/5.x/docs/getting_started.md
If you install the SDK manually, include the provided autoloader file. This allows PHP to find and load the SDK's classes without Composer.
```php
require_once __DIR__ . '/path/to/php-graph-sdk/src/Facebook/autoload.php';
```
--------------------------------
### Include Composer Autoloader
Source: https://github.com/facebookarchive/php-graph-sdk/blob/5.x/docs/getting_started.md
Include the Composer autoloader file in your PHP script to automatically load the Facebook SDK classes. This is essential after installing via Composer.
```php
require_once __DIR__ . '/vendor/autoload.php';
```
--------------------------------
### Make Graph API GET Request
Source: https://github.com/facebookarchive/php-graph-sdk/blob/5.x/docs/getting_started.md
Illustrates how to make a GET request to the Facebook Graph API, specifically the '/me' endpoint, using the SDK. It shows how to set a default access token and retrieve the user's information as a GraphUser object.
```php
$fb = new Facebook\Facebook([/* . . . */]);
// Sets the default fallback access token so we don't have to pass it to each request
$fb->setDefaultAccessToken('{access-token}');
try {
$response = $fb->get('/me');
$userNode = $response->getGraphUser();
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
echo 'Logged in as ' . $userNode->getName();
```
--------------------------------
### Manually Include SDK Autoloader with Custom Path
Source: https://github.com/facebookarchive/php-graph-sdk/blob/5.x/docs/getting_started.md
If the SDK's autoloader cannot detect the source directory, define the source directory path using a constant before including the autoloader.
```php
define('FACEBOOK_SDK_V4_SRC_DIR', __DIR__ . '/facebook-sdk-v5/');
require_once __DIR__ . '/facebook-sdk-v5/autoload.php';
```
--------------------------------
### Initialize Facebook SDK Service
Source: https://github.com/facebookarchive/php-graph-sdk/blob/5.x/docs/getting_started.md
Initialize the `FacebookFacebook` service with your application ID, app secret, and default Graph API version. This is the primary step to interact with the Facebook API.
```php
$fb = new Facebook\Facebook([
'app_id' => '{app-id}',
'app_secret' => '{app-secret}',
'default_graph_version' => 'v2.10',
]);
```
--------------------------------
### Obtain Facebook Access Token via Redirect (login.php)
Source: https://github.com/facebookarchive/php-graph-sdk/blob/5.x/docs/getting_started.md
This snippet demonstrates how to generate a Facebook login URL using `FacebookRedirectLoginHelper` on the login page. It requires the Facebook SDK and session support. The `getLoginUrl()` method takes the redirect URL and optional permissions as arguments.
```php
$fb = new Facebook\Facebook([/* . . . */]);
$helper = $fb->getRedirectLoginHelper();
$permissions = ['email', 'user_likes']; // optional
$loginUrl = $helper->getLoginUrl('http://{your-website}/login-callback.php', $permissions);
echo 'Log in with Facebook!';
```
--------------------------------
### Obtain Access Token from JavaScript Cookie
Source: https://github.com/facebookarchive/php-graph-sdk/blob/5.x/docs/getting_started.md
Demonstrates how to retrieve an access token set by the Facebook SDK for JavaScript via a cookie. It includes error handling for Graph API and SDK-specific exceptions. Ensure the JavaScript SDK is initialized with `{cookie:true}`.
```php
$fb = new Facebook\Facebook([/* . . . */]);
$helper = $fb->getJavaScriptHelper();
try {
$accessToken = $helper->getAccessToken();
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
if (isset($accessToken)) {
// Logged in
}
```
--------------------------------
### Handle Facebook Login Redirect and Get Access Token (login-callback.php)
Source: https://github.com/facebookarchive/php-graph-sdk/blob/5.x/docs/getting_started.md
This snippet shows how to retrieve the access token from the redirect callback URL using `FacebookRedirectLoginHelper`. It includes error handling for `FacebookResponseException` and `FacebookSDKException`. The obtained access token is stored in the session.
```php
$fb = new Facebook\Facebook([/* . . . */]);
$helper = $fb->getRedirectLoginHelper();
try {
$accessToken = $helper->getAccessToken();
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
if (isset($accessToken)) {
// Logged in!
$_SESSION['facebook_access_token'] = (string) $accessToken;
// Now you can redirect to another page and use the
// access token from $_SESSION['facebook_access_token']
}
```
--------------------------------
### Install Facebook SDK for PHP with Composer
Source: https://github.com/facebookarchive/php-graph-sdk/blob/5.x/README.md
This command installs the Facebook PHP SDK using Composer, the dependency manager for PHP. Ensure Composer is installed on your system.
```sh
composer require facebook/graph-sdk
```
--------------------------------
### Facebook SDK Video Upload Parameters and Example
Source: https://github.com/facebookarchive/php-graph-sdk/blob/5.x/docs/reference/Facebook.md
This section details the parameters required for uploading videos using the Facebook PHP SDK, including target node, file path, metadata, access token, and Graph API version. It also provides a practical PHP code example demonstrating a chunked video upload and error handling.
```APIDOC
uploadVideo($target, $pathToFile, $metadata, $accessToken, $maxTransferTries, $graphVersion)
Parameters:
$target: The ID or alias of the target node (user ID, page ID, event ID, group ID, or 'me').
$pathToFile: The absolute or relative path to the video file to upload.
$metadata: Metadata associated with the Video node (e.g., title, description).
$accessToken: The access token to use for the request. Falls back to the default access token if available.
$maxTransferTries: The number of times to retry uploading a chunk if the Graph API responds with a resumable error (defaults to 5).
$graphVersion: The version of the Graph API to use (resumable uploads available from v2.3 onwards).
Return Value:
An array containing 'video_id' (the ID of the video node) and 'success' (a boolean indicating successful transfer).
Error Handling:
Throws FacebookResponseException if a chunk upload fails after retries.
```
```php
$data = [
'title' => 'My awesome video',
'description' => 'More info about my awesome video.',
];
try {
$response = $fb->uploadVideo('me', '/path/to/video.mp4', $data, '{user-access-token}');
} catch(Facebook\Exceptions\FacebookSDKException $e) {
echo 'Error: ' . $e->getMessage();
exit;
}
echo 'Video ID: ' . $response['video_id'];
```
--------------------------------
### Get Access Token and Signed Request from Page Tab
Source: https://github.com/facebookarchive/php-graph-sdk/blob/5.x/docs/examples/access_token_from_page_tab.md
This snippet demonstrates how to initialize the Facebook SDK, obtain a Page Tab Helper, and retrieve the access token, page ID, admin status, and signed request from a page tab context. It includes error handling for Facebook SDK and Graph API exceptions.
```php
$fb = new Facebook\Facebook([
'app_id' => '{app-id}',
'app_secret' => '{app-secret}',
'default_graph_version' => 'v2.10',
]);
$helper = $fb->getPageTabHelper();
try {
$accessToken = $helper->getAccessToken();
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
if (! isset($accessToken)) {
echo 'No OAuth data could be obtained from the signed request. User has not authorized your app yet.';
exit;
}
// Logged in
echo '
Page ID
';
var_dump($helper->getPageId());
echo 'User is admin of page
';
var_dump($helper->isAdmin());
echo 'Signed Request
';
var_dump($helper->getSignedRequest());
echo 'Access Token
';
var_dump($accessToken->getValue());
```
--------------------------------
### Installing PHP Code Sniffer Globally
Source: https://github.com/facebookarchive/php-graph-sdk/blob/5.x/CONTRIBUTING.md
Installs PHP Code Sniffer globally using Composer, a tool used to enforce PSR-2 coding standards. This is a prerequisite for checking code style.
```bash
$ composer global require squizlabs/php_codesniffer
```
--------------------------------
### Basic Facebook Graph API GET Request
Source: https://github.com/facebookarchive/php-graph-sdk/blob/5.x/README.md
This PHP code snippet demonstrates how to initialize the Facebook SDK and make a basic GET request to the '/me' endpoint to retrieve user profile information. It includes error handling for both Graph API and SDK-specific exceptions.
```php
require_once __DIR__ . '/vendor/autoload.php'; // change path as needed
$fb = new \Facebook\Facebook([
'app_id' => '{app-id}',
'app_secret' => '{app-secret}',
'default_graph_version' => 'v2.10',
//'default_access_token' => '{access-token}', // optional
]);
// Use one of the helper classes to get a Facebook\Authentication\AccessToken entity.
// $helper = $fb->getRedirectLoginHelper();
// $helper = $fb->getJavaScriptHelper();
// $helper = $fb->getCanvasHelper();
// $helper = $fb->getPageTabHelper();
try {
// Get the \Facebook\GraphNodes\GraphUser object for the current user.
// If you provided a 'default_access_token', the '{access-token}' is optional.
$response = $fb->get('/me', '{access-token}');
} catch(\Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(\Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
$me = $response->getGraphUser();
echo 'Logged in as ' . $me->getName();
```
--------------------------------
### Facebook Canvas Helper Initialization
Source: https://github.com/facebookarchive/php-graph-sdk/blob/5.x/docs/reference/FacebookCanvasHelper.md
Demonstrates how to initialize the Facebook Canvas Helper using the Facebook SDK. This is the starting point for using canvas-specific functionalities.
```php
$fb = new Facebook\Facebook([/* */]);
$canvasHelper = $fb->getCanvasHelper();
```
--------------------------------
### Generate Facebook Login URL
Source: https://github.com/facebookarchive/php-graph-sdk/blob/5.x/docs/examples/facebook_login.md
This snippet shows how to initialize the Facebook SDK and generate a login URL with specified permissions. It requires the Facebook SDK for PHP and app credentials.
```php
$fb = new Facebook\Facebook([
'app_id' => '{app-id}',
'app_secret' => '{app-secret}',
'default_graph_version' => 'v2.10',
]);
$helper = $fb->getRedirectLoginHelper();
$permissions = ['email']; // Optional permissions
$loginUrl = $helper->getLoginUrl('https://example.com/fb-callback.php', $permissions);
echo 'Log in with Facebook!';
```
--------------------------------
### Facebook SDK PHP Batch Request
Source: https://github.com/facebookarchive/php-graph-sdk/blob/5.x/docs/examples/batch_request.md
Demonstrates sending multiple Facebook Graph API requests in a single batch. It includes fetching user profile, likes, events, posting to feed, and retrieving photos. The example utilizes JSONPath to reference data from previous requests within subsequent ones.
```php
'{app-id}',
'app_secret' => '{app-secret}',
'default_graph_version' => 'v2.10',
]);
// Since all the requests will be sent on behalf of the same user,
// we'll set the default fallback access token here.
$fb->setDefaultAccessToken('user-access-token');
/**
* Generate some requests and then send them in a batch request.
*/
// Get the name of the logged in user
$requestUserName = $fb->request('GET', '/me?fields=id,name');
// Get user likes
$requestUserLikes = $fb->request('GET', '/me/likes?fields=id,name&limit=1');
// Get user events
$requestUserEvents = $fb->request('GET', '/me/events?fields=id,name&limit=2');
// Post a status update with reference to the user's name
$message = 'My name is {result=user-profile:$.name}.' . "\n\n";
$message .= 'I like this page: {result=user-likes:$.data.0.name}.' . "\n\n";
$message .= 'My next 2 events are {result=user-events:$.data.*.name}.';
$statusUpdate = ['message' => $message];
$requestPostToFeed = $fb->request('POST', '/me/feed', $statusUpdate);
// Get user photos
$requestUserPhotos = $fb->request('GET', '/me/photos?fields=id,source,name&limit=2');
$batch = [
'user-profile' => $requestUserName,
'user-likes' => $requestUserLikes,
'user-events' => $requestUserEvents,
'post-to-feed' => $requestPostToFeed,
'user-photos' => $requestUserPhotos,
];
echo 'Make a batch request
' . "\n\n";
try {
$responses = $fb->sendBatchRequest($batch);
} catch (Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch (Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
foreach ($responses as $key => $response) {
if ($response->isError()) {
$e = $response->getThrownException();
echo 'Error! Facebook SDK Said: ' . $e->getMessage() . "\n\n";
echo '
Graph Said: ' . "\n\n";
var_dump($e->getResponse());
} else {
echo "
(" . $key . ") HTTP status code: " . $response->getHttpStatusCode() . "
\n";
echo "Response: " . $response->getBody() . "
\n\n";
echo "
\n\n";
}
}
```
--------------------------------
### FacebookPageTabHelper Usage Example
Source: https://github.com/facebookarchive/php-graph-sdk/blob/5.x/docs/reference/FacebookPageTabHelper.md
Demonstrates how to initialize the FacebookPageTabHelper and retrieve the signed request payload.
```php
$fb = new Facebook\Facebook([/* */]);
$pageHelper = $fb->getPageTabHelper();
$signedRequest = $pageHelper->getSignedRequest();
if ($signedRequest) {
$payload = $signedRequest->getPayload();
var_dump($payload);
}
```
--------------------------------
### GraphEdge Deep Pagination Example
Source: https://github.com/facebookarchive/php-graph-sdk/blob/5.x/docs/reference/GraphEdge.md
Illustrates deep pagination within GraphEdge, allowing iteration over nested lists of nodes, such as paginating through pages and their likes.
```php
$pagesEdge = $response->getGraphEdge();
// Only grab 5 pages
$maxPages = 5;
$pageCount = 0;
do {
echo 'Page #' . $pageCount . ':
' . "\n\n";
foreach ($pagesEdge as $page) {
var_dump($page->asArray());
$likes = $page['likes'];
do {
echo 'Likes:
' . "\n\n";
var_dump($likes->asArray());
} while ($likes = $fb->next($likes));
}
$pageCount++;
} while ($pageCount < $maxPages && $pagesEdge = $fb->next($pagesEdge));
```
--------------------------------
### Get Graph API Response as Decoded Array
Source: https://github.com/facebookarchive/php-graph-sdk/blob/5.x/docs/getting_started.md
Demonstrates how to retrieve the raw JSON response from a Graph API request as a decoded PHP array. This is an alternative to processing the response as a GraphNode object.
```php
try {
$response = $fb->get('/me');
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// . . .
exit;
}
$plainOldArray = $response->getDecodedBody();
```
--------------------------------
### FacebookClient Instance Methods
Source: https://github.com/facebookarchive/php-graph-sdk/blob/5.x/docs/reference/FacebookClient.md
Provides documentation for the instance methods of the FacebookClient class, including methods for retrieving and setting the HTTP client handler, enabling beta mode, and sending individual or batch requests to the Graph API.
```APIDOC
FacebookClient Instance Methods:
getHttpClientHandler()
Returns the instance of Facebook\HttpClients\FacebookHttpClientInterface that the service is using.
setHttpClientHandler(Facebook\HttpClients\FacebookHttpClientInterface $client)
Injects a custom HTTP client that implements the Facebook\HttpClients\FacebookHttpClientInterface into the service.
enableBetaMode(boolean $enable = true)
Configures the service to send requests to beta Graph API endpoints (e.g., graph.beta.facebook.com).
sendRequest(Facebook\FacebookRequest $request)
Sends a single, non-batch request to the Graph API. Handles request encoding (form or multipart) and returns a Facebook\FacebookResponse object. Throws FacebookSDKException for pre-request errors or FacebookResponseException for API errors.
sendBatchRequest(Facebook\FacebookBatchRequest $batchRequest)
Sends a batch of requests to the Graph API. Handles request encoding and returns a Facebook\FacebookBatchResponse object. Similar exception handling as sendRequest for pre-request and API errors.
```
--------------------------------
### Obtain Facebook Access Token from Canvas Context
Source: https://github.com/facebookarchive/php-graph-sdk/blob/5.x/docs/getting_started.md
This snippet demonstrates how to get an access token for a user within a Facebook Canvas application using `FacebookCanvasHelper`. It handles potential Graph API errors and SDK validation issues. The access token is obtained from the signed request payload.
```php
$fb = new Facebook\Facebook([/* . . . */]);
$helper = $fb->getCanvasHelper();
try {
$accessToken = $helper->getAccessToken();
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
if (isset($accessToken)) {
// Logged in.
}
```
--------------------------------
### Basic Graph API Requests
Source: https://github.com/facebookarchive/php-graph-sdk/blob/5.x/docs/reference/Facebook.md
Shows examples of sending GET, POST, and DELETE requests to the Facebook Graph API using the instantiated `FacebookFacebook` service object.
```php
// Send a GET request
$response = $fb->get('/me');
// Send a POST request
$response = $fb->post('/me/feed', ['message' => 'Foo message']);
// Send a DELETE request
$response = $fb->delete('/{node-id}');
```
--------------------------------
### Instantiate Facebook Service
Source: https://github.com/facebookarchive/php-graph-sdk/blob/5.x/docs/reference/Facebook.md
Demonstrates how to create a new instance of the `FacebookFacebook` service class by providing an array of configuration options to the constructor.
```php
$fb = new Facebook\Facebook([
'app_id' => '{app-id}',
'app_secret' => '{app-secret}',
'default_graph_version' => 'v2.10',
// . . .
]);
```
--------------------------------
### Run PHPUnit Tests
Source: https://github.com/facebookarchive/php-graph-sdk/blob/5.x/README.md
These commands show how to execute the project's tests using PHPUnit. The first command runs all tests, while the second command skips integration tests, which require an internet connection.
```bash
$ ./vendor/bin/phpunit
```
```bash
$ ./vendor/bin/phpunit --exclude-group integration
```
--------------------------------
### Instantiating FacebookClient
Source: https://github.com/facebookarchive/php-graph-sdk/blob/5.x/docs/reference/FacebookClient.md
Demonstrates how to obtain an instance of the FacebookClient. It can be retrieved from the main Facebook service class or created directly by providing an HTTP client handler and an optional beta mode flag.
```php
$fb = new Facebook\Facebook([/* */]);
$fbClient = $fb->getClient();
```
```php
$fbClient = new Facebook\FacebookClient($httpClientHandler, $enableBeta = false);
```
--------------------------------
### Extend Short-Lived Access Token
Source: https://github.com/facebookarchive/php-graph-sdk/blob/5.x/docs/getting_started.md
Shows how to exchange a short-lived Facebook access token for a long-lived one using the OAuth2Client. Short-lived tokens typically last 2 hours, while long-lived tokens last about 60 days.
```php
$oAuth2Client = $fb->getOAuth2Client();
// Exchanges a short-lived access token for a long-lived one
$longLivedAccessToken = $oAuth2Client->getLongLivedAccessToken('{access-token}');
```
--------------------------------
### Running Tests
Source: https://github.com/facebookarchive/php-graph-sdk/blob/5.x/CONTRIBUTING.md
This command executes the test suite for the Facebook PHP SDK using PHPUnit. Ensure all tests pass before submitting a pull request.
```bash
$ ./vendor/bin/phpunit
```
--------------------------------
### Obtain Facebook Access Token from JavaScript SDK
Source: https://github.com/facebookarchive/php-graph-sdk/blob/5.x/docs/getting_started.md
This snippet illustrates how to retrieve an access token from the Facebook SDK for JavaScript using the `FacebookJavaScriptHelper`. This is useful when authentication is handled client-side. The `getAccessToken()` method returns an `AccessToken` entity.
```php
$fb = new Facebook\Facebook([/* . . . */]);
$helper = $fb->getJavaScriptHelper();
try {
$accessToken = $helper->getAccessToken();
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
if (isset($accessToken)) {
// Logged in.
}
```
--------------------------------
### Initialize FacebookRedirectLoginHelper
Source: https://github.com/facebookarchive/php-graph-sdk/blob/5.x/docs/reference/FacebookRedirectLoginHelper.md
Demonstrates how to obtain an instance of the FacebookRedirectLoginHelper from the Facebook service.
```php
$fb = new Facebook\Facebook([/* . . . */]);
$helper = $fb->getRedirectLoginHelper();
```
--------------------------------
### Facebook Service Configuration Options
Source: https://github.com/facebookarchive/php-graph-sdk/blob/5.x/docs/reference/Facebook.md
Provides a comprehensive example of initializing the `FacebookFacebook` service with a full set of configuration options, including app ID, secret, access token, beta mode, graph version, HTTP client, and persistent data handlers.
```php
$fb = new Facebook\Facebook([
'app_id' => '{app-id}',
'app_secret' => '{app-secret}',
'default_access_token' => '{access-token}',
'enable_beta_mode' => true,
'default_graph_version' => 'v2.10',
'http_client_handler' => 'guzzle',
'persistent_data_handler' => 'memory',
'url_detection_handler' => new MyUrlDetectionHandler(),
'pseudo_random_string_generator' => new MyPseudoRandomStringGenerator(),
]);
```
--------------------------------
### PHP Script to Get Access Token from Cookie
Source: https://github.com/facebookarchive/php-graph-sdk/blob/5.x/docs/examples/access_token_from_javascript.md
A PHP script that uses the Facebook SDK for PHP to retrieve an access token from a cookie set by the JavaScript SDK. It handles potential exceptions during the token retrieval process and stores the token in the session.
```php
# /js-login.php
$fb = new Facebook\Facebook([
'app_id' => '{app-id}',
'app_secret' => '{app-secret}',
'default_graph_version' => 'v2.10',
]);
$helper = $fb->getJavaScriptHelper();
try {
$accessToken = $helper->getAccessToken();
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
if (! isset($accessToken)) {
echo 'No cookie set or no OAuth data could be obtained from cookie.';
exit;
}
// Logged in
echo 'Access Token
';
var_dump($accessToken->getValue());
$_SESSION['fb_access_token'] = (string) $accessToken;
// User is logged in!
// You can redirect them to a members-only page.
//header('Location: https://example.com/members.php');
```
--------------------------------
### FacebookJavaScriptHelper Instance Methods
Source: https://github.com/facebookarchive/php-graph-sdk/blob/5.x/docs/reference/FacebookJavaScriptHelper.md
API documentation for the instance methods of the FacebookJavaScriptHelper class.
```APIDOC
FacebookJavaScriptHelper:
__construct(FacebookApp $app, FacebookClient $client, $graphVersion = null)
Validates and decodes the signed request from the JavaScript SDK cookie upon instantiation.
getAccessToken(FacebookClient $client)
Checks the signed request for authentication data and attempts to retrieve an access token.
Returns: Facebook\AccessToken|null
getUserId()
Returns the user's ID from the signed request if present, valid, and the user has authorized the app.
Returns: string|null
getSignedRequest()
Returns the signed request as a Facebook\SignedRequest entity if present.
Returns: Facebook\SignedRequest|null
getRawSignedRequest()
Returns the raw encoded signed request as a string or null.
Returns: string|null
```
--------------------------------
### Handle Facebook Login Callback and Access Token
Source: https://github.com/facebookarchive/php-graph-sdk/blob/5.x/docs/examples/facebook_login.md
This snippet demonstrates how to handle the callback from Facebook after a user logs in. It retrieves the access token, validates it, and exchanges it for a long-lived token. It includes error handling for SDK and Graph API exceptions. Requires the Facebook SDK for PHP and app credentials.
```php
$fb = new Facebook\Facebook([
'app_id' => '{app-id}',
'app_secret' => '{app-secret}',
'default_graph_version' => 'v2.10',
]);
$helper = $fb->getRedirectLoginHelper();
try {
$accessToken = $helper->getAccessToken();
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
if (! isset($accessToken)) {
if ($helper->getError()) {
header('HTTP/1.0 401 Unauthorized');
echo "Error: " . $helper->getError() . "\n";
echo "Error Code: " . $helper->getErrorCode() . "\n";
echo "Error Reason: " . $helper->getErrorReason() . "\n";
echo "Error Description: " . $helper->getErrorDescription() . "\n";
} else {
header('HTTP/1.0 400 Bad Request');
echo 'Bad request';
}
exit;
}
// Logged in
echo 'Access Token
';
var_dump($accessToken->getValue());
// The OAuth 2.0 client handler helps us manage access tokens
$oAuth2Client = $fb->getOAuth2Client();
// Get the access token metadata from /debug_token
$tokenMetadata = $oAuth2Client->debugToken($accessToken);
echo 'Metadata
';
var_dump($tokenMetadata);
// Validation (these will throw FacebookSDKException's when they fail)
$tokenMetadata->validateAppId($config['app_id']);
// If you know the user ID this access token belongs to, you can validate it here
//$tokenMetadata->validateUserId('123');
$tokenMetadata->validateExpiration();
if (! $accessToken->isLongLived()) {
// Exchanges a short-lived access token for a long-lived one
try {
$accessToken = $oAuth2Client->getLongLivedAccessToken($accessToken);
} catch (Facebook\Exceptions\FacebookSDKException $e) {
echo "Error getting long-lived access token: " . $e->getMessage() . "
\n\n";
exit;
}
echo 'Long-lived
';
var_dump($accessToken->getValue());
}
$_SESSION['fb_access_token'] = (string) $accessToken;
// User is logged in with a long-lived access token.
// You can redirect them to a members-only page.
//header('Location: https://example.com/members.php');
```
--------------------------------
### Facebook Graph API Request Methods (GET, POST, DELETE)
Source: https://github.com/facebookarchive/php-graph-sdk/blob/5.x/docs/reference/Facebook.md
Provides documentation for sending GET, POST, and DELETE requests to the Facebook Graph API. These methods handle endpoint specification, access tokens, optional ETags for caching, and Graph versioning. The POST and DELETE methods also accept an array of parameters for the request body.
```APIDOC
FacebookFacebookResponse get(string $endpoint, string|AccessToken|null $accessToken, string|null $eTag, string|null $graphVersion)
Sends a GET request to Graph and returns a Facebook\FacebookResponse.
Parameters:
$endpoint: The url to send to Graph without the version prefix (required).
$accessToken: The access token (as a string or AccessToken entity) to use for the request. If none is provided, the SDK will assume the value from the default_access_token configuration option if it was set.
$eTag: [Graph supports eTags](https://developers.facebook.com/docs/marketing-api/etags). Set this to the eTag from a previous request to get a 304 Not Modified response if the data has not changed.
$graphVersion: This will overwrite the Graph version that was set in the default_graph_version configuration option.
Example:
$fb->get('/me');
Facebook\FacebookResponse post(string $endpoint, array $params, string|AccessToken|null $accessToken, string|null $eTag, string|null $graphVersion)
Sends a POST request to Graph and returns a Facebook\FacebookResponse.
Parameters:
$endpoint: The url to send to Graph without the version prefix (required).
$params: The associative array of params you want to send in the body of the POST request.
$accessToken: The access token (as a string or AccessToken entity) to use for the request. If none is provided, the SDK will assume the value from the default_access_token configuration option if it was set.
$eTag: [Graph supports eTags](https://developers.facebook.com/docs/marketing-api/etags). Set this to the eTag from a previous request to get a 304 Not Modified response if the data has not changed.
$graphVersion: This will overwrite the Graph version that was set in the default_graph_version configuration option.
Example:
$response = $fb->post('/me/feed', ['message' => 'Foo message']);
Facebook\FacebookResponse delete(string $endpoint, array $params, string|AccessToken|null $accessToken, string|null $eTag, string|null $graphVersion)
Sends a DELETE request to Graph and returns a Facebook\FacebookResponse.
Parameters:
$endpoint: The url to send to Graph without the version prefix (required).
$params: The associative array of params you want to send in the body of the POST request.
$accessToken: The access token (as a string or AccessToken entity) to use for the request. If none is provided, the SDK will assume the value from the default_access_token configuration option if it was set.
$eTag: [Graph supports eTags](https://developers.facebook.com/docs/marketing-api/etags). Set this to the eTag from a previous request to get a 304 Not Modified response if the data has not changed.
$graphVersion: This will overwrite the Graph version that was set in the default_graph_version configuration option.
Example:
$response = $fb->delete('/{node-id}', ['object' => '1234']);
```
--------------------------------
### Facebook Graph API Cursor Pagination
Source: https://github.com/facebookarchive/php-graph-sdk/blob/5.x/docs/examples/pagination_basic.md
This snippet demonstrates how to fetch data from the Facebook Graph API and paginate through the results using the Facebook SDK for PHP. It shows how to make an initial request, process the first page of results, and then fetch the next page of data.
```php
$fb = new Facebook\Facebook([
'app_id' => '{app-id}',
'app_secret' => '{app-secret}',
'default_graph_version' => 'v2.10',
]);
try {
// Requires the "read_stream" permission
$response = $fb->get('/me/feed?fields=id,message&limit=5');
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
// Page 1
$feedEdge = $response->getGraphEdge();
foreach ($feedEdge as $status) {
var_dump($status->asArray());
}
// Page 2 (next 5 results)
$nextFeed = $fb->next($feedEdge);
foreach ($nextFeed as $status) {
var_dump($status->asArray());
}
```
--------------------------------
### Batch File Upload with Facebook SDK for PHP
Source: https://github.com/facebookarchive/php-graph-sdk/blob/5.x/docs/examples/batch_upload.md
This snippet shows how to upload multiple files (photos and videos) in a single batch request using the Facebook SDK for PHP. It initializes the SDK, sets an access token, constructs the batch request with file uploads, sends the batch, and processes the responses, including error handling.
```php
$fb = new Facebook\Facebook([
'app_id' => '{app-id}',
'app_secret' => '{app-secret}',
'default_graph_version' => 'v2.10',
]);
// Since all the requests will be sent on behalf of the same user,
// we'll set the default fallback access token here.
$fb->setDefaultAccessToken('user-access-token');
$batch = [
'photo-one' => $fb->request('POST', '/me/photos', [
'message' => 'Foo photo',
'source' => $fb->fileToUpload('/path/to/photo-one.jpg'),
]),
'photo-two' => $fb->request('POST', '/me/photos', [
'message' => 'Bar photo',
'source' => $fb->fileToUpload('/path/to/photo-two.jpg'),
]),
'video-one' => $fb->request('POST', '/me/videos', [
'title' => 'Baz video',
'description' => 'My neat baz video',
'source' => $fb->videoToUpload('/path/to/video-one.mp4'),
]),
];
try {
$responses = $fb->sendBatchRequest($batch);
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
foreach ($responses as $key => $response) {
if ($response->isError()) {
$e = $response->getThrownException();
echo 'Error! Facebook SDK Said: ' . $e->getMessage() . "\n\n";
echo '
Graph Said: ' . "\n\n";
var_dump($e->getResponse());
} else {
echo "
(" . $key . ") HTTP status code: " . $response->getHttpStatusCode() . "
\n";
echo "Response: " . $response->getBody() . "
\n\n";
echo "
\n\n";
}
}
```
--------------------------------
### FacebookFile Class Constructor and Factory
Source: https://github.com/facebookarchive/php-graph-sdk/blob/5.x/docs/reference/FacebookFile.md
Demonstrates how to instantiate the FacebookFile class for file uploads, either directly or using the Facebook super service factory method. It also explains the optional maxLength and offset parameters for partial uploads.
```APIDOC
Facebook\FileUpload\FacebookFile(string $pathToFile, int $maxLength = -1, int $offset = -1)
Represents a local or remote file to be uploaded with a request to Graph.
Parameters:
$pathToFile: The path to the file to upload.
$maxLength: The maximum length of the file to upload (optional, defaults to -1 for full file).
$offset: The offset to start reading the file from (optional, defaults to -1 for beginning).
```
```php
use Facebook\FileUpload\FacebookFile;
// Direct instantiation
$myFileToUpload = new FacebookFile('/path/to/file.jpg');
// Using the factory method
$fb = new Facebook\Facebook(/* . . . */);
$myFileToUpload = $fb->fileToUpload('/path/to/file.jpg');
```
--------------------------------
### PHP Facebook SDK Batch Request for Multiple Users/Pages
Source: https://github.com/facebookarchive/php-graph-sdk/blob/5.x/docs/examples/batch_request.md
This example demonstrates how to send multiple, unrelated Facebook Graph API requests in a single batch request using the PHP SDK. It shows how to include requests for different users and pages by providing distinct access tokens for each request within the batch array. This is efficient for managing operations across multiple entities simultaneously.
```php
'{app-id}',
'app_secret' => '{app-secret}',
'default_graph_version' => 'v2.10',
]);
$batch = [
$fb->request('GET', '/me?fields=id,name', 'user-access-token-one'),
$fb->request('GET', '/me?fields=id,name', 'user-access-token-two'),
$fb->request('GET', '/me?fields=id,name', 'page-access-token-one'),
$fb->request('GET', '/me?fields=id,name', 'page-access-token-two'),
];
try {
$responses = $fb->sendBatchRequest($batch);
} catch (Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch (Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
foreach ($responses as $key => $response) {
if ($response->isError()) {
$e = $response->getThrownException();
echo 'Error! Facebook SDK Said: ' . $e->getMessage() . "\n\n";
echo '
Graph Said: ' . "\n\n";
var_dump($e->getResponse());
} else {
echo "
(" . $key . ") HTTP status code: " . $response->getHttpStatusCode() . "
\n";
echo "Response: " . $response->getBody() . "
\n\n";
echo "
\n\n";
}
}
?>
```
--------------------------------
### FacebookCanvasHelper Instance Methods
Source: https://github.com/facebookarchive/php-graph-sdk/blob/5.x/docs/reference/FacebookCanvasHelper.md
Provides details on the instance methods available for the FacebookCanvasHelper class, including their signatures and purposes.
```APIDOC
FacebookCanvasHelper::getAccessToken(): Facebook\AccessToken|null
Description:
Checks the signed request for authentication data and tries to obtain an access token.
Returns:
Facebook\AccessToken|null: The access token if found, otherwise null.
```
```APIDOC
FacebookCanvasHelper::getUserId(): string|null
Description:
A convenience method for obtaining a user's ID from the signed request if present. This will only return the user's ID if a valid signed request can be obtained and decrypted and the user has already authorized the app.
Returns:
string|null: The user ID if available, otherwise null.
```
```APIDOC
FacebookCanvasHelper::getAppData(): string|null
Description:
Gets the value that is set in the `app_data` property if present.
Returns:
string|null: The app data string if present, otherwise null.
```
```APIDOC
FacebookCanvasHelper::getSignedRequest(): Facebook\SignedRequest|null
Description:
Returns the signed request as an instance of `Facebook\SignedRequest` if present.
Returns:
Facebook\SignedRequest|null: The SignedRequest object if available, otherwise null.
```
```APIDOC
FacebookCanvasHelper::getRawSignedRequest(): string|null
Description:
Returns the raw encoded signed request as a `string` if present in the POST variables or `null`.
Returns:
string|null: The raw signed request string if available, otherwise null.
```
--------------------------------
### Get App Data
Source: https://github.com/facebookarchive/php-graph-sdk/blob/5.x/docs/reference/FacebookCanvasHelper.md
Retrieves the value of the 'app_data' property from the signed request if it exists.
```php
$appData = $canvasHelper->getAppData();
```
--------------------------------
### GraphEdge Method Reference
Source: https://github.com/facebookarchive/php-graph-sdk/blob/5.x/docs/reference/GraphEdge.md
Provides documentation for key methods of the GraphEdge class, including retrieving metadata, cursors for pagination, and total counts.
```APIDOC
Facebook\GraphNodes\GraphEdge:
getMetaData(): array
- Returns additional raw data associated with an edge.
- Example:
$metaData = $graphEdge->getMetaData();
getNextCursor(): string|null
- Returns the $.paging.cursors.after value or null if it does not exist.
- Useful for bookmarking pagination positions.
- Example:
$nextCursor = $graphEdge->getNextCursor();
// Returns: MMAyDDM5NjA0OTEyMDc0OTM=
getPreviousCursor(): string|null
- Returns the $.paging.cursors.before value or null if it does not exist.
- Example:
$previousCursor = $graphEdge->getPreviousCursor();
// Returns: ODOxMTUzMjQzNTg5zzU5
getTotalCount(): int|null
- Returns the total count of results from the summary, if available (e.g., when 'summary=true' is used).
- Returns null if the summary or total count is not present.
- Example:
$response = $fb->get('/{post-id}/likes?summary=true');
$likesEdge = $response->getGraphEdge();
$totalCount = $likesEdge->getTotalCount();
// Returns: 10
```