how to create login with facebook button using php

I am creating a web application using PHP and I would like to add login with facebook button in it's login page , how can i do it?


Asked by:- pika
: 4815 At:- 5/22/2017 7:00:55 AM
php facebook login

2 Answers
profileImage Answered by:- vikas_jk

Ok so I am not a very good PHP developer, but here is possible solution

1 » Goto and Click Add a New App.
» Choose Website
» Choose Name for you App and Click Create New Facebook App ID
» Choose a category for you App and click Create App ID
» Now Click Skip Quick Test

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

3. Create a login page

$fb = new Facebook\Facebook([
  'app_id' => '{app-id}', // Replace {app-id} with your app id
  'app_secret' => '{app-secret}',
  'default_graph_version' => 'v2.2',

$helper = $fb->getRedirectLoginHelper();

$permissions = ['email']; // Optional permissions
$loginUrl = $helper->getLoginUrl('', $permissions);

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

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()

$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();
} catch(Facebook\Exceptions\FacebookSDKException $e) {
  // When validation fails or other local issues
  echo 'Facebook SDK returned an error: ' . $e->getMessage();
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';
// 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');

5. 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.

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();
} catch(Facebook\Exceptions\FacebookSDKException $e) {
  echo 'Facebook SDK returned an error: ' . $e->getMessage();
$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.

Another method 
go to this URL

At:- 5/22/2017 7:24:35 AM

profileImage Answered by:- robertlook
  • Need to go and click on add a new group button to make the app ID.
  • Choose Website
  • Give an app name and click on
  • Create New Facebook App ID
  • Click on Create App ID
  • Click on Skip Quick Test

Now open the fbconfig.php file and add your app ID and app Secret. this tutorial facebook SDK PHP.

    FacebookSession::setDefaultApplication( 'your app ID','App Secrete ' );
    // login helper with redirect_uri
       $helper = new FacebookRedirectLoginHelper('You web address' );

Finally, fbconfig.php file as shown below code how to login with Facebook -

       // added in v4.0.0
       require_once 'autoload.php';
       use Facebook\FacebookSession;
       use Facebook\FacebookRedirectLoginHelper;
       use Facebook\FacebookRequest;
       use Facebook\FacebookResponse;
       use Facebook\FacebookSDKException;
       use Facebook\FacebookRequestException;
       use Facebook\FacebookAuthorizationException;
       use Facebook\GraphObject;
       use Facebook\Entities\AccessToken;
       use Facebook\HttpClients\FacebookCurlHttpClient;
       use Facebook\HttpClients\FacebookHttpable;
       // init app with app id and secret
       FacebookSession::setDefaultApplication( 'your app ID','App Secrete ' );
       // login helper with redirect_uri
       $helper = new FacebookRedirectLoginHelper('' );
       try {
          $session = $helper->getSessionFromRedirect();
       }catch( FacebookRequestException $ex ) {
          // When Facebook returns an error
       }catch( Exception $ex ) {
          // When validation fails or other local issues
       // see if we have a session
       if ( isset( $session ) ) {
          // graph api request for user data
          $request = new FacebookRequest( $session, 'GET', '/me' );
          $response = $request->execute();
          // get response
          $graphObject = $response->getGraphObject();
          $fbid = $graphObject->getProperty('id');           // To Get Facebook ID
          $fbfullname = $graphObject->getProperty('name');   // To Get Facebook full name
          $femail = $graphObject->getProperty('email');      // To Get Facebook email ID
          /* ---- Session Variables -----*/
          $_SESSION['FBID'] = $fbid;
          $_SESSION['FULLNAME'] = $fbfullname;
          $_SESSION['EMAIL'] =  $femail;
          /* ---- header location after session ----*/
          header("Location: index.php");
       }else {
          $loginUrl = $helper->getLoginUrl();
          header("Location: ".$loginUrl);

And your Login page

       $_SESSION['FBID'] = NULL;
       $_SESSION['EMAIL'] =  NULL;
       header("Location: index.php");        


    <html xmlns:fb = "">
          <title>How To Login With Facebook In Php With Example -</title>
             href = "" rel = "stylesheet">
          <?php if ($_SESSION['FBID']): ?>      <!--  After user login  -->
             <div class = "container">
                <div class = "hero-unit">
                   <h1>Hello <?php echo $_SESSION['USERNAME']; ?></h1>
                   <p>Welcome to "facebook login" tutorial</p>
                <div class = "span4">
                   <ul class = "nav nav-list">
                      <li class = "nav-header"><img src=""></li>
                      <li><img src = "<?php 
                         echo $_SESSION['FBID']; ?>/picture"></li>
                      <li class = "nav-header">Facebook ID</li>
                      <li><?php echo  $_SESSION['FBID']; ?></li>
                      <li class = "nav-header">Facebook fullname</li>
                      <li><?php echo $_SESSION['FULLNAME']; ?></li>
                      <li class = "nav-header">Facebook Email</li>
                      <li><?php echo $_SESSION['EMAIL']; ?></li>
                      <div><a href="logout.php">Logout</a></div>
             <?php else: ?>     <!-- Before login --> 
             <div class = "container">
                <h1>Login with Facebook</h1>
                   <a href = "fbconfig.php"><img src=""></a>
          <?php endif ?>

That's it, you are done.

To check working example, see this link

At:- 11/8/2020 10:01:14 AM
Please always mention complete steps with code, not just link, thanks 0
By : vikas_jk - at :- 11/9/2020 11:56:40 AM

Login/Register to answer
Register directly by posting answer/details

Full Name *

Email *

By posting your answer you agree on privacy policy & terms of use