Chat with us, powered by LiveChat

This website uses cookies

Our website, platform and/or any sub domains use cookies to understand how you use our services, and to improve both your experience and our marketing relevance.

How To Add Facebook Login to PHP Website

October 13, 2016

5 Min Read
Reading Time: 5 minutes

Long registration forms that are a huge hassle to fill and a real pain to validate are now a thing of the past. These days, developers have worked around this thorny UX issue by using Facebook Login for their applications.

facebook login in php

Facebook offers an excellent alternate to the traditional form based login process that has long been a part of the PHP applications. The idea is very simple; you just have to put a Facebook button on the registration page. Next, save the user data after successful login. In this article, I will explain how you can add Facebook Login to PHP apps and get the users’ data.

The process has four steps:

  1. Create a Facebook application.
  2. Create an application on the server.
  3. Download Facebook SDK.
  4. Initialize SDK and get user information.

You might be interested at: How To Create A Facebook Messenger Bot

Create an Application in Facebook

To implement Facebook Login system for the application, the first step is the creation of an app through the Facebook account.

Sign into the Facebook and go to developer.Facebook.com .

Once there, create an app.

create app

Click Add New App button and select Website as the platform.

select platform

Host Your PHP Apps With Us For 10x Faster Performance

Don’t Let Your Customers Run Away With The Downtimes. Deploy With Us Today!

Enter the app’s name, an email id and select a category for the application. Now click Create App Id button. This will create an app in Facebook.

add facebook app

Now go to Settings, where the App Secret and App ID could be found. These ids will be used in the PHP application. Remember to add the website’s URL in App Domains.

Down the page, Click the Add Platform tab. Add website as a platform and enter the URL of the

website again.

add new domain

This finishes the creation of the Facebook App. The next step is to create a server on a fast and reliable hosting platform. I have opted for Cloudways PHP stack server.

Create an Application on Server

To create a PHP server on Cloudways, signup and launch a PHP server on it. For reference, I have created a GIF

php server stack

Related: How To Host PHP On DigitalOcean

Visit the server and launch the SSH terminal. Login to SSH by using the master credentials.

cloudways application management

Go to the application folder by running the following command

$ cd applications/{your application folder}/private_html/

php hosting signup

Download Facebook SDK

Composer is the recommended method of  installing libraries on the platform and I will use it to install Facebook SDK.The first step is the creation of a composer file. In the SSH terminal run composer init command and add the required information to it. It will create a composer.json file in the application folder. Add the following code in composer.json.

{

 "require" : {

   "facebook/graph-sdk" : "~5.0"

 }

}

Now run composer install command in SSH to finalize installation of Facebook SDK.

Initialize SDK and Get User Information

It is now time to initialize Facebook SDK and get access_token from Facebook. After authenticating the token, the user info will be fetched and the view will be redirected to the profile page that shows the user information.

Create two files in the application folder; Index.php and Profile.php.

Add the following code to index.php file. Comments are added to explain the code.

<?php

//initialize facebook sdk

require 'vendor/autoload.php';

session_start();

$fb = new Facebook\Facebook([

 'app_id' => '1214799411888113',

 'app_secret' => '286f08b36691768f859a70e788f4ceda',

 'default_graph_version' => 'v2.5',

]);

$helper = $fb->getRedirectLoginHelper();

$permissions = ['email']; // optional

try {

if (isset($_SESSION['facebook_access_token'])) {

$accessToken = $_SESSION['facebook_access_token'];

} else {

  $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 (isset($_SESSION['facebook_access_token'])) {

$fb->setDefaultAccessToken($_SESSION['facebook_access_token']);

} else {

// getting short-lived access token

$_SESSION['facebook_access_token'] = (string) $accessToken;

  // OAuth 2.0 client handler

$oAuth2Client = $fb->getOAuth2Client();

// Exchanges a short-lived access token for a long-lived one

$longLivedAccessToken = $oAuth2Client->getLongLivedAccessToken($_SESSION['facebook_access_token']);

$_SESSION['facebook_access_token'] = (string) $longLivedAccessToken;

// setting default access token to be used in script

$fb->setDefaultAccessToken($_SESSION['facebook_access_token']);

}

// redirect the user to the profile page if it has "code" GET variable

if (isset($_GET['code'])) {

header('Location: profile.php');

}

// getting basic info about user

try {

$profile_request = $fb->get('/me?fields=name,first_name,last_name,email');

$requestPicture = $fb->get('/me/picture?redirect=false&height=200'); //getting user picture

$picture = $requestPicture->getGraphUser();

$profile = $profile_request->getGraphUser();

$fbid = $profile->getProperty('id');           // To Get Facebook ID

$fbfullname = $profile->getProperty('name');   // To Get Facebook full name

$fbemail = $profile->getProperty('email');    //  To Get Facebook email

$fbpic = "<img src='".$picture['url']."' class='img-rounded'/>";

# save the user nformation in session variable

$_SESSION['fb_id'] = $fbid.'</br>';

$_SESSION['fb_name'] = $fbfullname.'</br>';

$_SESSION['fb_email'] = $fbemail.'</br>';

$_SESSION['fb_pic'] = $fbpic.'</br>';

} catch(Facebook\Exceptions\FacebookResponseException $e) {

// When Graph returns an error

echo 'Graph returned an error: ' . $e->getMessage();

session_destroy();

// redirecting user back to app login page

header("Location: ./");

exit;

} catch(Facebook\Exceptions\FacebookSDKException $e) {

// When validation fails or other local issues

echo 'Facebook SDK returned an error: ' . $e->getMessage();

exit;

}

} else {

// replace your website URL same as added in the developers.Facebook.com/apps e.g. if you used http instead of https and you used            

$loginUrl = $helper->getLoginUrl('http://phpstack-21306-56790-161818.cloudwaysapps.com', $permissions);
echo '<a href="' . $loginUrl . '">Log in with Facebook!</a>';

}

?>

Once done, go to the application URL in browser. You will see the Facebook button for login. Click it and the page will redirect to Facebook login page. Sign into the Facebook account. After successful login, the page will be redirected to the profile page.

Add the following code to profile.php to show the retrieved information. For the purpose of this tutorial, I will retrieve user id, Facebook profile picture, name and email.

<?php

session_start();

?>

<head>

     <title>Login with Facebook</title>

     <link

        href = "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"

        rel = "stylesheet">

  </head>

  <body>     

  <?php if($_SESSION['fb_id']) {?>

        <div class = "container">

           <div class = "jumbotron">

              <h1>Hello <?php echo $_SESSION['fb_name']; ?></h1>

              <p>Welcome to Cloudways</p>

           </div>

              <ul class = "nav nav-list">

                 <h4>Image</h4>

                 <li><?php echo $_SESSION['fb_pic']?></li>

                 <h4>Facebook ID</h4>

                 <li><?php echo  $_SESSION['fb_id']; ?></li>

                 <h4>Facebook fullname</h4>

                 <li><?php echo $_SESSION['fb_name']; ?></li>

                 <h4>Facebook Email</h4>

                 <li><?php echo $_SESSION['fb_email']; ?></li>

              </ul>

          </div>

<?php } ?>

  </body>

</html>

As you can see, the information is presented in a very simple format.

Conclusion

In this tutorial, I demonstrated how to integrate Facebook Login button in your PHP apps. This will do away with the hassles of filling in and parsing long registration forms. If you need to ask a question about the code or wish to add to the conversation, please leave a comment below.

Share your opinion in the comment section. COMMENT NOW

Share This Article

Launch PHP websites without the worry of Server Management.

Pre-Installed Optimized Stack with Git, Composer & SSH

Shahroze Nawaz

Shahroze is a PHP Community Manager at Cloudways - A Managed PHP Hosting Platform. Besides his work life, he loves movies and travelling. You can email him at shahroze.nawaz@cloudways.com

Get Our Newsletter
Be the first to get the latest updates and tutorials.

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

BFCM 2019