How to login with Facebook SDK using PHP or Javascript ?

  In this tutorial, Uses the PHP with Facebook graph API v9.0 , PHP SDK of Facebook Graph API allows to perform the all the required task needed


Today, web owners want to create their website as robust, how quickly users subscribe to websites. Nowadays users want an easy way to login or subscribe to the website. If the website has asked the user to input their details to subscribe which is a very cumbersome job to the user, because of this issue user are not going to log in to your website, to overcome these issues we can use the login with Facebook using PHP or Javascript which helps in to reduce the extra activity to subscribe the websites. With just a single click user can subscribe to your website using login with Facebook.

There are Two way to achieve in this tutorial :

  1. Login with Facebook using PHP (Server-Side) ?
  2. Login with Facebook using JavaScript (Client-Side) ?

Table of Contents

How to login with Facebook using PHP ?

In this tutorial, Uses the PHP with Facebook graph API v9.0 , PHP SDK of Facebook Graph API allows to perform the all the required task needed. Use latest Graph API version of Facebook API, you can get the from click me This tutorial using the Facebook Graph API V9.0 with PHP SDK, To implement the Registration Process or Login with Facebook.

Required Facebook graph API v9.0 :

  • PHP version should be 5.6 or greater.
  • Facebook PHP SDK ( Get it from php-graph-sdk )

Structure of PHP Pages, that we use to login with Facebook using PHP:

Directory

Create Facebook Application:

STEP 1: First, need to create a Facebook Developer Account Click me .
STEP 2: Click on My Apps and login with your Facebook Account on the Top-Left Navigation Bar of Facebook For Developers website.

Facebook Developer

STEP 3: You will get as shown below, If you are not getting then you need to create Facebook Developer Accounts. Then you will get as shown below, Now click on Create App :

Facebook Developer Admin Panel

STEP 4: Select the Category from given options shown below, In this Tutorial using Manage Business Integration and click continue button :

Manage Business Integrations

STEP 5: Now, Fill in the Required Information field for your Application, You need to enter the Following Data:

  1. App Display Name
  2. App Contact Email
  3. App Purpose
  4. Business Manager Account (Optional)
Create An APP

 After filling required information click on Create App button.

STEP 6: You can see the App Dashboard something like this :

Add Product to Your App

  Note – Add Additional Products to Your App as shown in Pictures.

STEP 7: Now, click on Facebook Login from Sidebar menu then navigate to Settings, you need to enter your Redirect_URI_FACEBOOK inside the Valid OAuth Redirect URIs Field as you can see below:

Client OAuth Login

STEP 8: Click on Settings from Side-Menu and go to the Basic, To use this app in your website you need to add the add your domain (e.g codenaive.com) to the domains field as well as the privacy page URL of your website ( e.g: https://www.codenaive.com/privacy ) inside the field of Privacy Policy URL then click on Save Changes as shown below :

Facebook Developer Basic Settings

STEP 9: Remember the APP ID and Secret Key that is used to authenticate your website to login the User :

STEP 10: Now, We are ready but before start we need to set the Facebook Permission , Click on App review on Side Menu Bar then navigate to the Permission and Features . You can see the list of Access Level of Facebook API, there are some basic things that you can access without any review for example public_profile and email , If you need to manage the Posts of user with your website then you need to send the Request of Advanced Access for your website then Facebook developer will review your requests application, For a review you need to submit the additional information of your website you can get from here click me, In this tutorial, we are working on Basic Access.

Setting website and Config.php files :

Now, You have your own App ID as well as Secret Key, fill the data with your App Id and Secret Key.

   
 
<?php
/* ********* Facebook API Configuration and  Basic Site Settings  *********/


define('Facebook_APP_ID', '266585808180094');
define('Facebook_APP_SECRET', '73ae3feb13c37eacd891c9232cef25ce');
define('REDIRECT_URI_Facebook', 'https://codenaive.com');


// ----------------Start session-----------------
if(!session_id()){
    session_start();
}

//-------------------- Include the autoloader provided in the SDK----------
require_once __DIR__ . '/vendor/autoload.php';

// Include required libraries
use Facebook\Facebook;
use Facebook\Exceptions\FacebookResponseException;
use Facebook\Exceptions\FacebookSDKException;

// --------Call Facebook API-------------------
$fb = new Facebook(array(
    'app_id' => Facebook_APP_ID,
    'app_secret' => Facebook_APP_SECRET,
    'default_graph_version' => 'v3.2',
));

//----------------- Get redirect login helper-----------------
$helper = $fb->getRedirectLoginHelper();

// -------------------- get access token------------------------
try {
    if(isset($_SESSION['facebook_access_token'])){
        $accessTokenFB = $_SESSION['facebook_access_token'];
    }
  else{
          $accessTokenFB = $helper->getAccessToken();
    }
} catch(FacebookResponseException $e) {
     echo 'Graph returned an error: ' . $e->getMessage();
      exit;
} catch(FacebookSDKException $e) {
    echo 'Facebook SDK returned an error: ' . $e->getMessage();
      exit;
}

?>
							
							
						 					

Login and Handle Facebook user data in index.php file :

Index.php file handle the login process whether the user authenticated or not ? If the user authorized then Login to this PHP page and then handle the User Data. In this file First it check whether the access token of Facebook exist in $accessTokenFB Variable or not, if it exist in $accessTokenFB variable then simply Login otherwise get the Login URL of Facebook using getLoginUrl() function of Facebook Graph API handler. The getLoginUrl() helps in to get the login URL using the App credentials by which user can able to login into your website. Once user logged in with Facebook Account they can able to logout with URL generated by function of Facebook Graph API using getLogoutUrl() Function . In case there are some issues then you will get the error message something like “Unable to login due to technical error….”.

Use the $_SESSIONS variable to store user’s data ( Facebook using PHP ) :

Uses the Following $_SESSIONS to store the Tokens as well as user data:

  1. $_SESSION[‘facebook_access_token’]
  2. $_SESSION[‘imgURL’]
  3. $_SESSION[‘id’]
  4. $_SESSION[’email’]
  5. $_SESSION[‘first_name’]
  6. $_SESSION[‘last_name’]
   
 

<?php
/************************ Using Facebook Graph API v9.0 ******************************/
require_once 'Config.php';

$addFacebook="";
$outputFacebook="";

error_reporting(E_ALL);
ini_set('display_errors', 1);
 if(isset($accessTokenFB)){
    if(isset($_SESSION['facebook_access_token'])){
        $fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
    }
    else{
        //-----------Store  short-lived access token in session variable-------------
        $_SESSION['facebook_access_token'] = (string) $accessTokenFB;
        
       //------------OAuth 2.0 client handler used to helps to manage access tokens-----------------
        $oAuth2Client = $fb->getOAuth2Client();
        
        //-------- Exchanges a short-lived access token for a long-lived ------------
        $longLivedAccessToken = $oAuth2Client->getLongLivedAccessToken($_SESSION['facebook_access_token']);
        $_SESSION['facebook_access_token'] = (string) $longLivedAccessToken;
        
        //------------- Set access token default ------------------------
        $fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
    }
    
    // Redirect the user back to the same page if url has "code" parameter in query string
    if(isset($_GET['code'])){
        header('Location: /');
    }
    
    //------------ Getting user's profile Data as /me with filters from Facebook-----------
    try{
 
         $graphResponse = $fb->get('/me?fields=name,first_name,last_name,email,link,picture');
         $ReterivedData = $graphResponse->getGraphUser();
         
         $_SESSION['imgURL']=$ReterivedData['picture']['url'];
         $_SESSION['id']=$ReterivedData['id'];
         $_SESSION['email']=$ReterivedData['email'];
         $_SESSION['first_name']=$ReterivedData['first_name'];
         $_SESSION['last_name']=$ReterivedData['last_name'];
    } 
    catch(FacebookResponseException $e) {
        echo 'Graph returned an error: ' . $e->getMessage();
        session_destroy();
        //--------------- Redirect user back to app login page-------------
        header("Location: /");
        exit;
    } 
    catch(FacebookSDKException $e) {
        echo 'Facebook SDK returned an error: ' . $e->getMessage();
        exit;
    }
    
   
    $logoutURL = $helper->getLogoutUrl($accessTokenFB,REDIRECT_URI_FB.'/logoutFacebook.php');
    
    
    // ----------------------Handle user data here ----------------------------------
    //------------------- Display the fetched Facebook profile data
   if(!empty($ReterivedData)){
        $outputFacebook  = '<h1>Facebook Profile Details</h1>';
        $outputFacebook .= '<div class="container">';
        $outputFacebook .= '<img src="'.$ReterivedData['picture']['url'].'"/>';
        $outputFacebook .= '<p><b>Email ID:</b> '.$ReterivedData['email'].'</p>';
        $outputFacebook .= '<p><b>Facebook ID:</b> '.$ReterivedData['id'].'</p>';
        $outputFacebook .= '<p><b>Name:</b> '.$ReterivedData['first_name'].' '.$ReterivedData['last_name'].'</p>';
         $outputFacebook .= '<a class="btn btn-primary" href="'.$logoutURL.'"> <i class="fab fa-facebook-f"></i> Logout Facebook </a>';
        $outputFacebook .= '</div>';
        
         
       // $addFacebook = 
        
    }
    else{
        $outputFacebook = '<h3 style="color:red">Unable to login due to technical error.....</h3>';
    }
}

else{
    //-------------------- Get the login url--------------------------
    $permissions = array('email'); // Add more permissions here if needed.
    $loginURL = $helper->getLoginUrl(REDIRECT_URI_FB, $permissions);
    
    //---------------------Render Facebook login button---------------------
    $addFacebook = '<a class="btn btn-primary" href="'.htmlspecialchars($loginURL).'"> <i class="fab fa-facebook-f"></i> Add Facebook </a>';
}

?>
<!DOCTYPE html>
<html lang="en-US">
<head>
    <meta charset="utf-8">
    <title>Login with Facebook using SDK by Codenaive</title>
     <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
	
	<link rel="stylesheet" rel="noreferrer" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css" integrity="sha384-AYmEC3Yw5cVb3ZcuHtOA93w35dYTsvhLPVnYs9eStHfGJvOvKxVfELGroGkvsg+p" crossorigin="anonymous"/>
</head>    
<body>
    <h1>Example : Login with Facebook using SDK by Codenaive</h1>
    <?php echo $outputFacebook; ?>
    <?php echo $addFacebook ?>
</body>
    
</html>
							
							
							
									
							
						 					

Create Logout.php File :

Assume, user logged in using Facebook Account to your website, now we need to add the Logout PHP file as shown below that helps in to unset or clear all the SESSION variables by which user can logout from your website when needed.

   
 
<?php

require_once 'Config.php';

// Remove access token from session
unset($_SESSION['facebook_access_token']);

// Remove user data from session
unset($_SESSION['imgURL']);
unset($_SESSION['id']);
unset($_SESSION['email']);
unset($_SESSION['first_name']);
unset($_SESSION['last_name']);


// Redirect to the homepage
header("Location: / ");

?>

Output

Output 1
Output 2

Conclusion :

In this tutorial, we learned about how the Facebook Graph API works and how we can use it with PHP, by which users can subscribe to the website as well as login website with a Facebook account. We also cover how to use this technique to improve the subscription of the website.

Leave a Reply

Your email address will not be published. Required fields are marked *