go top

How to Create a Facebook Login for Your Website Using PHP v5

With the increasing number of online websites, the number of accounts that each one of us has is also rising. People don’t want to memorize passwords for every site that they have an account with. To let users log in to your website more efficiently without another username/password combination for them, let them log in with their Facebook account! After a user logs in to Facebook and authenticates your website, you can then start a login session. Let’s dig into how to code this up using the Facebook SDK for PHP v5.

1. Create Facebook App

To start, you must register your website with Facebook at https://developers.facebook.com/apps/. Add a new “Website” app, and fill out the required informational fields. After you have created the App ID and entered your website’s URL, click Next. Then, skip the rest of the quick start - we will implement the code later. On the next page, you will be shown your App ID and App Secret. Take note of these; they will be used below.

If you are testing locally while developing, create and use a second Facebook app for local tests. When creating this second app, select “Is this a test version of another app?” to associate it as a testing version of the first app.

2. Install Facebook SDK to Your PHP Project

Now that your “Facebook app” is set up, it’s time to start coding. Facebook has made implementation very simple by providing an SDK for handling most of the heavy lifting. Installation instructions can be found at https://developers.facebook.com/docs/php/gettingstarted.

3. Create Log In Button

Users must be redirected to the Facebook site to log in and authenticate your website. What URL do you send them to? The Facebook SDK will create it for you. Place the following code on the page where you want the login button to appear:

// Ensure that sessions are started by this point using session_start()

<?php
$fb = new Facebook\Facebook([
'app_id' => '{app-id}',
'app_secret' => '{app-secret}',
'default_graph_version' => 'v2.2',
]);

$helper = $fb->getRedirectLoginHelper();

$permissions = []; // Optional information that your app can access, such as 'email'
$loginUrl = $helper->getLoginUrl('https://example.com/fb-callback.php', $permissions);

echo '<a href="' . htmlspecialchars($loginUrl) . '">Log in with Facebook</a>';
?>


(Example adapted from Facebook for Developers docs)

Take special note to the {app-id} and {app-secret} portions of this code snippet. This is where you place your App ID and App Secret from Step 1. Keep in mind that the App Secret is secret! Don’t share this with anyone. As a further security measure, it is good practice to store this value in a file somewhere outside of the web root, and then include it into the login page.

After a user is logged in and has authenticated your website, Facebook needs to know which page to redirect the user to; this will be the page where you start a login session. Replace 'https://example.com/fb-callback.php' with the callback URL on your website. Details on how to craft this page are found in the next step.

By default, your website will be able to access an authenticated user’s publicly-available Facebook information, such as their name. If you need to pull more information, such as the email, then you will need to include these permissions in the $permissions variable. For a list of permission options, see https://developers.facebook.com/docs/facebook-login/permissions. Once you’ve added the permission, see “Pull Personal Information from Facebook” below for how to actually retrieve the information.

The last line of the code snippet prints a “Login with Facebook” button to your web page. Customize this login button to match your website’s UI.

4. Create Callback Page

The callback page is where your website will ensure that the user is logged in to Facebook and has authenticated your website. If so, then you can authenticate them into your website.

// Ensure that sessions are started by this point using session_start()

<?php
$fb = new Facebook\Facebook([
'app_id' => '{app-id}',
'app_secret' => '{app-secret}',
'default_graph_version' => 'v2.2',
]);

$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
// 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);

// Get user’s Facebook ID
$userId = $tokenMetadata->getField('user_id');
?>


(Example adapted from Facebook for Developers docs)

As before, replace {app-id} and {app-secret} with their corresponding values. This code confirms that there were no login or authentication issues, and then gets the user’s Facebook ID - a unique identifier for each user - and stores it in the $userId variable.

You can now create a users table for your website and associate each logged-in user to an entry in that table by using the Facebook ID as a key.

The following is an example of how to register a user on the first login, and then load user information from your table upon sequential logins. First, check to see if the user’s Facebook ID exists in your website’s user registration table. If the ID does NOT exist in your table, then register the user. Create an entry in the table with the Facebook ID as a key (you can also add personal information from Facebook - see the next section). You can now look up the user by their ID at the next log in. If the ID already DOES exist in your table, then the user was previously registered to your website. Retrieve the user’s record from the table as necessary (by using the Facebook user ID as the key).

Then, start a login session on your website.

Pull Personal Information from Facebook

When registering a user to your website, it is often useful to store personal information into your database, such as the user’s name. The following code shows how to get a person’s name and user ID from the Facebook API. This example uses the $accessToken that was set in the code example in the previous section.

<?php
try {
// Returns a `Facebook\FacebookResponse` object
$response = $fb->get('/me?fields=id,name', $accessToken);
} catch(Facebook\Exceptions\FacebookResponseException $e) {
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}

$user = $response->getGraphUser();

$userId = $user['id']; // Retrieve user Id
$userName = $user['name']; // Retrieve user name
?>


The last two variables will contain the user ID and username. To pull additional information about the user, add the type to the API call (/me?fields=id,name) and then read the value(s) from the $user variable. Keep in mind that if you want to pull non-public information, then you must include the proper permissions. See “Create Log In Button” for more details.

Access Token Authentication

Note that if you don’t need an external database to store information for each user, you can use the Facebook access token alone as an authentication mechanism (i.e. by storing it in the session). For more information, please visit Facebook for Developers docs

Make Your App Public

Once you’ve tested your implementation, make your Facebook app public at https://developers.facebook.com/apps/. Go to the App Review tab and enable “Make [App] public?”

Conclusion

Congratulations, you have just saved your users one less password to remember. Although you should always allow users to log into your website without Facebook and don't forget to harden your PHP for a secure site, adding it as an option will not only allow users to log in faster, but they will be more likely to sign up!

16 Comments to "How to Create a Facebook Login for Your Website Using PHP v5"

  • debasis

    debasis

    July 31, 2018 at 09:35 am

    okk

  • yogesh

    yogesh

    January 6, 2018 at 08:31 am

    nice article keep on blogging...

  • Hadi

    Hadi

    October 29, 2017 at 11:43 am

    Hi
    I tried to implement like you locally but I gave the following Error:

    Graph returned an error: URL can not be loaded: The domain of this URL is not present in the domains of the app. To load this URL, add all domains and subdomains of your app in the appdomain field in your app settings.

    I am using virtual host on Xampp.

    Bests
    Hadi

    • waseem habash

      waseem habash

      October 2, 2018 at 12:20 pm

      you must first go to :
      https://developers.facebook.com/

      then , add your app with it's url

      hope that's help

  • RK

    RK

    October 15, 2017 at 04:39 am

    In step #3, following line should be added in the beginning of login.php file.
    require_once __DIR__ . '/vendor/autoload.php';
    Without this, 'Login with Facebook' link won't appear.

  • Kamlesh

    Kamlesh

    July 2, 2017 at 21:37 pm

    thanks for information...

  • Kerry Audisho

    Kerry Audisho

    July 1, 2017 at 16:37 pm

    Thanks for the information! Is there a way to login to my site with Facebook PAGE?

  • Php Professional

    Php Professional

    June 19, 2017 at 07:33 am

    Nice tutorial. This tutorial was really useful to create a login form with facebook in my business site. Put this code on my site and it works. Its useful to beginners. Thanks for this tutorial.

    • Ginn Chou

      Ginn Chou

      June 19, 2017 at 09:06 am

      Hi there, how do you integrate this code into a website?

  • Ameni

    Ameni

    June 12, 2017 at 12:52 pm

    Thanks Lucas for this tutorial.
    how can i also get a facebook user history??please any help

  • Bram

    Bram

    April 16, 2017 at 18:38 pm

    No matter what I try I keep getting the same error when clicking the "login with facebook" link

    This page doesn't work
    www.facebook.com can't process this request.
    HTTP ERROR 500

  • Ginn

    Ginn

    March 30, 2017 at 10:05 am

    Hi Lukas, thanks for this tutorial!

    Is there a way I can collect the user's email and add it to my autoresponder like Aweber?

    Regards,
    Ginn

next

Add your comment

Captcha
    • Free Scripts

      Add great new functionalities to your website with our Free Scripts collection.

      Free scripts
    • Free Web Templates

      Browse our FREE Website Templates and use them to create your new sweeping website!

      Free website templates