Connecting to the Facebook API using the Facebook PHP SDK

When developing web applications, you may need to connect to the Facebook API to gather information or make posts for the user. In this article, we will be teaching you how to connect to the Facebook API using the Facebook PHP SDK.

Note: If you have not already done so, be sure to prepare the SDK on your development environment by following our guide on obtaining the Facebook SDK.

Full code example

<?php
// Begin loading the necessary files for the Facebook SDK.
require ( 'autoload.php' );

// Load the required PHP classes from the Facebook SDK.
use Facebook\FacebookSession;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookRequest;

// Start the session
session_start();

// Initialize the Facebook app using the application ID and secret.
FacebookSession::setDefaultApplication( 'xxxxxxxxxxxxxx','xxxxxxxxxxxxxxxxxxxxxxxxxxx' );

// Define Facebook's login helper and redirect back to our page.
$helper = new FacebookRedirectLoginHelper( 'https://local.wordpress.dev/fb/index.php' );

// Check to ensure our session was started correctly and the access token exists.
if ( isset( $_SESSION ) && isset( $_SESSION['fb_token'] ) ) {
// Using the access token, create a new session.
$session = new FacebookSession( $_SESSION['fb_token'] );

// Determine if the defined session is indeed valid.
if ( !$session->validate() ) {
$session = null;
}
}
// Check if an active session exists.
if ( !isset( $session ) || $session === null ) {
// If no session exists, let's try to create one.
$session = $helper->getSessionFromRedirect();
}

// Make sure we have a session started.
if ( isset( $session ) ) {
// Save the session
$_SESSION['fb_token'] = $session->getToken();

// Create a new Facebook session using our token.
$session = new FacebookSession( $session->getToken() );
echo 'Connected to Facebook!';
} else {
// Show login url
echo '<a href="' . $helper->getLoginUrl( array( 'email', 'user_friends' ) ) . '">Login</a>';
}

Walking through the code

Connecting to the Facebook SDK

First, we will need to connect to the Facebook SDK to load all of the required libraries. Thankfully, much of the work is already done for us with the autoload.php file that is included with the Facebook SDK. We simply need to include it and reference the required connection classes like so:

// Begin loading the necessary files for the Facebook SDK.
require ( 'autoload.php' );

// Load the required PHP classes from the Facebook SDK.
use Facebook\FacebookSession;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookRequest;

As you can see here, we used the require() PHP function to include the autoload.php file.

Then, as our connection needs to load a session with Facebook, we have set our code to include the FacebookSessionFacebookRedirectLoginHelper, and FacebookRequest PHP classes to appropriately connect as well as request data from Facebook’s API.

Starting the session

Now that we have included the required libraries in our code, we need to open a new session. To do so, simply call the session_star() function:

// Start the session
session_start();

Initializing the connection to the Facebook API

So far, we have successfully started a session, but we’re still not yet connected to the Facebook API. To begin the connection, you will need to send your API key to Facebook’s API. The following lines will handle passing the API key on the Facebook:

// Initialize the Facebook app using the application ID and secret.
FacebookSession::setDefaultApplication( 'xxxxxxxxxxxxxx','xxxxxxxxxxxxxxxxxxxxxxxxxxx' );

Within this line, you will need to add your Application ID and Secret that is obtained from the Facebook Developers site. If you do not already have an Application ID, you may follow our article on obtaining a Facebook API key.

Now that the application is initialized and your credentials are verified with the Facebook API, a session needs to be created with Facebook. When creating sessions with the Facebook API, the user will be sent to Facebook to log in and authorize the application, then redirected back to your application. In the following lines, we are opening a session with Facebook and preparing to run requests to the Facebook API.

// Define Facebook's login helper and redirect back to our page.
$helper = new FacebookRedirectLoginHelper( 'https://local.wordpress.dev/fb/index.php' );

// Check to ensure our session was started correctly and the access token exists.
if ( isset( $_SESSION ) && isset( $_SESSION['fb_token'] ) ) {
// Using the access token, create a new session.
$session = new FacebookSession( $_SESSION['fb_token'] );

// Determine if the defined session is indeed valid.
if ( !$session->validate() ) {
$session = null;
}
}
// Check if an active session exists.
if ( !isset( $session ) || $session === null ) {
// If no session exists, let's try to create one.
$session = $helper->getSessionFromRedirect();
}

Prompt the user to login or display data

In the next lines, we then need to check to see if there is an active session, then display the content appopriately. If the user is not yet logged in and provided permissions to the application, the user will be prompted with a link to log in and will be returned to the page as per the FacebookRedirectLoginHelper URL. Once the user is returned, they will have a session active and will then be shown Connected to Facebook! in their browser.

// Make sure we have a session started.
if ( isset( $session ) ) {
// Save the session
$_SESSION['fb_token'] = $session->getToken();

// Create a new Facebook session using our token.
$session = new FacebookSession( $session->getToken() );
echo 'Connected to Facebook!';
} else {
// Show login url
echo '<a href="' . $helper->getLoginUrl( array( 'email', 'user_friends' ) ) . '">Login</a>';
}

Where do I go from here?

Now that you know how to easily connect to the Facebook API using the Facebook SDK for PHP, you can now make queries to Facebook to generate information on users.

9 thoughts on “Connecting to the Facebook API using the Facebook PHP SDK

  1. I implemented the same, i got no errors but even after authentication i see “login” link …Am i missing something here ?

    Why isn’t session being set?

    1. Hello Praharsh,

      We unfortunately cannot provide any programming support here. If your indeed authenticating and and a session has been opened, then you may be missing something in your code that completes the login process. You will need to re-visit your code or speak with a developer who can review it.

      Kindest regards,
      Arnel C.

  2. I haven’t received any errors, however I just don’t have the facebook button appearing. As for the index file, I made a separate one which is located within the same folder as the autoload.php file. Opencart appears to have another index file on the public.html root directory. Should the autoload.php and index.php be placed (or code added) to those on the root drive? Would I also then need to change some code to make sure it pulls up the rest of the information left in the facebook folder I created with the other SDK files?

    1. This article isn’t isn’t intended to show a button. It is intended to connect to the API and retrieve user information. Could you clarify what exactly you are trying to do?

  3. Hi Jeff, thanks for your fast reply. I have been trying to get this running for opencart v 2.0 without success.

    So far I have added the SDK files to a new directory named ‘facebook’ which is put on the root of the ‘public_html’ folder. I have then tried adding your code to an index.php file made within the root of ‘facebook folder.’ I’ve tried in a few other PHP files without success either. Hope to hear from you again,

    John

    1. What specific issues are you running into? Any errors? Also, be sure that you have the autoload.php file within the same directory as your index file that your connection code is within.

  4. Could you please explain where this code is meant to be placed? I know how to put it on the server, but your guide doesn’t explain where it needs to go. You mention the developers environment but that doesn’t make any sense. Could you elaborate on where it should be put. Thank you in advance.

    1. This code can simply go on whatever PHP file you want to connect to the Facebook SDK on. It’s truly all up to you as to what file you place it in.

Was this article helpful? Join the conversation!

Server Madness Sale
Score Big with Savings up to 99% Off

X