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

Our Services

At Blumoo Creative, our dedicated team of marketing specialists, encompassing areas such as ecommerce, pay-per-click, search engine optimization, lead generation, conversion rate optimization, performance marketing, and more are here to ensure that you get the results you want. We focus on data to guide all our discussions and choices, continuously refining and enhancing through rigorous testing and optimization processes.

  • seo content marketing icon

    SEO & Content Marketing

    Our expert SEO team and content writers, will craft a digital marketing strategy focused on driving conversions, drawing from our extensive experience in SEO consulting and strategy execution.

    Learn More
  • pay per click icon

    PPC: Google & Facebook Advertising

    Trust our Google Partner marketing experts to develop a tailored PPC campaign, including strategies for Google and Facebook ads, crafted to meet your business objectives and desired results.

    Learn More
  • social media marketing icon

    Social Media Marketing

    Our SMM experts will effectively maximize your conversion rates to provide a better user experience thanks to our unparalleled customer research and skilled team members.

    Learn More
  • web design & creative services icon

    Web Design & Creative Services

    Blumoo Creative's team of highly-skilled developers and graphic designers will provide your business with the professional, beautiful and unique look for every project that it deserves.

    Lean More
WORK WITH US

Learn More About the Work We’ve Done

  • Locals Tavern

    Boosts Organic Search Results & Visibility with Blumoo Creative.

  • remax realy logo

    92% Increase in Organic Traffic Through Content Marketing.

  • atlantic reclaimed lumber logo

    54% Revenue Growth Year Over Year by Implementing Content Optimizations.

  • buffalo wild wings logo

    Increases Post Engagement Rate by 400% with Blumoo Creative.

  • dutch bult homes logo

    44% Increase in Organic Sessions Through Technical SEO and On-Page Optimizations.

  • emerge ortho logo

    +75% Increase in Branded Searches and +200% Increase in Organic Traffic.

  • john deere logo

    Reduces Cost Per Click By 41.37% While Increasing Leads with Blumoo Creative.

  • krispy kreme logo

    220% Increase in Fund Raiser Participation Through Email Campaigns.

  • whitehead construction inc logo

    +450% Organic Traffic Increase Through Optimized Content - Globally!

  • trial card logo

    Lead your digital journey in the right direction.

  • six o'clok farms logo

    454% growth in Google Ads revenue after account restructure.

  • Lead your digital journey in the right direction.

    It's easy!

    Work With Us

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.