Setting up Facebook SDK with PHP - Not that bad!

Jun 3rd 2022
facebook programming background

Connecting to the Facebook API is easy using this simple library. You'll need a little programming knowledge, but once you have it set up your app will be able retrieve all kinds of information from users and post updates on their behalf!

Note: Be sure to prepare the SDK on your development environment, if you have not done so already.

Full Code Example


	
// 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 'Login';
}

Let's Look at This 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;

If you noticed, we used the require() PHP function to include the autoload.php file. If you are using a PHP framework like Codeigniter or Laravel, you may need alter this code a bit.

Then, as our connection needs to load a session with Facebook, we have set our code to include the FacebookSession, FacebookRedirectLoginHelper, 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 'Login';
	}
	

Where do I go from here?

That's up to you! Go make a peanut butter & jelly sandwich (I prefer jam), take a walk, go watch a movie... just kidding! 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.

thumbnail pic of Gregg Moore

Written by Gregg Moore

Gregg Moore is the founder/owner of Blumoo Creative, a digital marketing company. A ridiculously hard-working designer, developer & SEO specialist. He's also a bona fide master at eating chicken wings and watching sports at the same time! @GreggMoore23

WHY CHOOSE BLUMOO CREATIVE?

We're not your average boring web design company. We specialize in cutting-edge, innovative solutions that will exceed any expectations you may have for a website or online presence and make us stand out from other companies who just do "simple" work with little substance behind their output!

graphic of lightbulb thinking

INNOVATIVE

The web is our pasture. MOO! We design websites with creativity and innovation at the forefront of everything we do... from 2010 to infinity and beyond!

experince thumbs up approval

EXPERIENCE

We're not a team of robots delivering an uninspired, cookie-cutter website to every client. Our sites will be with fresh ideas ready-made just for your project!

graphic of dj playing music - fun

WE ARE FUN!

By working with a group of enthusiastic, creative and fun-loving nerds you'll be able to save yourself time as well as money all while enjoying life and keeping your sanity!

60,000+ Searches Happen Each Second

In 2024, SEO is not about ranking for popular terms; it’s about being found when it matters most. Our skilled SEO experts carefully research the right keywords for your business, ensuring you are gaining qualified traffic that converts to your bottom line.

93%
of online experiences begin with a search engine
75%
of people never scroll past the first page of results
61%
of users research a product before making a purchase

Are you losing business?

If you don’t have a professional website, your business is 87% less likely to succeed.

Let's Get Started!

We’re passionate about building the ideal custom approach for your brand that your customers will remember. From SEO-driven web design to expertly crafted copy and social media campaigns to awesome websites, it’s our mission to take your business to the next level.

We'll never share your email with anyone else.