Login with Facebook using PHP with Facebook SDK

We can use Facebook login to allow the users to get access into the websites. This page will explain you about login with facebook PHP SDK.

Facebook SDK for PHP

The facebook-php-graph-sdk/ directory contains the latest version (v5) of Facebook SDK for PHP. All the required files of Facebook PHP SDK v5 are included in our Facebook Login PHP source code. facebook-php-graph-sdk directory Download

File Structue

Facebook oauth login file structure

How to create Facebook App

1. Click here for create facebook App Id Facebook Developer

2. Click the My Apps link and select Add New App.
  • Enter the Display Name and Contact Email
  • Click on the Create App ID button
  • You will be redirected to the App Dashboard
3. Navigate to the Settings -> Basic page.
  • Specify the App Domains and select the Category of your App
  • Click the Save Changes
4. Navigate to the Add a Product page by clicking the PRODUCTS(+) link at the left navigation menu panel.
  • Select Facebook Login to Set Up
  • Select Web as the App platform
  • the Site URL and Save
5. Navigate to the Facebook Login -> Settings page
  • In the Valid OAuth Redirect URIs field, enter the Redirect URL
  • Click the Save Changes

Go to the Settings -> Basic page, note the App ID and App Secret. This App ID and App secret allow you to access the Facebook APIs.

Facebook oauth login file structure

config.php

<?php
/*
 * codrglass.com - Basic configuration and setting
 */

// Facebook API configuration
define('FB_APP_ID', 'Insert_Facebook_App_ID');
define('FB_APP_SECRET', 'Insert_Facebook_App_Secret');
define('FB_REDIRECT_URL', 'Callback_URL');

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

// Include the autoloader provided in the SDK
require_once __DIR__ . '/facebook-php-graph-sdk/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' => FB_APP_ID,
    'app_secret' => FB_APP_SECRET,
    'default_graph_version' => 'v3.2',
));

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

// Try to get access token
try {
    if(isset($_SESSION['facebook_access_token'])){
        $accessToken = $_SESSION['facebook_access_token'];
    }else{
          $accessToken = $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;
}

?>

index.php:

In this file, the API authentication and authorization process are handled using PHP


<?php
// Include configuration file
require_once 'config.php';

if(isset($accessToken)){
    if(isset($_SESSION['facebook_access_token'])){
        $fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
    }else{
        // Put short-lived access token in session
        $_SESSION['facebook_access_token'] = (string) $accessToken;
        
          // OAuth 2.0 client handler helps to manage access tokens
        $oAuth2Client = $fb->getOAuth2Client();
        
        // Exchanges a short-lived access token for a long-lived one
$longAToken=$oAuth2Client->getLongLivedAccessToken($_SESSION['facebook_access_token']);
$longLivedAccessToken =   $longAToken;  
$_SESSION['facebook_access_token'] = (string) $longLivedAccessToken;
        
        // Set default access token to be used in script
        $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: ./');
       $longLivedAccessToken = $longAToken;
    }
    
    // Getting user's profile info from Facebook
try {
 $graphResponse = $fb->get('/me?fields=name,first_name,last_name,email,link,gender,picture');
 $fbUser = $graphResponse->getGraphUser();
    } 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;
    }
    
   
    // Getting user's profile data
    $fbUserData = array();
    $fbUserData['oauth_uid']  = !empty($fbUser['id'])?$fbUser['id']:'';
    $fbUserData['first_name'] = !empty($fbUser['first_name'])?$fbUser['first_name']:'';
    $fbUserData['last_name']  = !empty($fbUser['last_name'])?$fbUser['last_name']:'';
    $fbUserData['email']      = !empty($fbUser['email'])?$fbUser['email']:'';
    $fbUserData['picture']    = !empty($fbUser['picture']['url'])?$fbUser['picture']['url']:'';
    $fbUserData['link']       = !empty($fbUser['link'])?$fbUser['link']:'';
   
    $userData = $fbUserData;
    
    // Storing user data in the session
    $_SESSION['userData'] = $userData;
    
    // Get logout url
    $logoutURL = $helper->getLogoutUrl($accessToken, FB_REDIRECT_URL.'logout.php');
    
    // Render Facebook profile data
    if(!empty($userData)){
        
        $_SESSION['userName'] =$userData['first_name'];
        $_SESSION['userPic']='<img src="'.$userData['picture'].'"/>';
        $_SESSION['userId']= '<p><b>Facebook ID:</b> '.$userData['oauth_uid'].'</p>';
        $_SESSION['userFName']= '<p><b>Name:</b> '.$userData['first_name'].'</p>';
        $_SESSION['userEmail']= '<p><b>Email:</b> '.$userData['email'].'</p>';
        $_SESSION['logOUT']= '<p><b>Logout from <a href="'.$logoutURL.'">Facebook</a></p>';
       
        header("Location:home-page.php");
        
    }else{
        $error_out = '<h3 style="color:red">Some problem occurred.</h3>';
    }
}else{
    // Get login url
    $permissions = ['email']; // Optional permissions
    $loginURL = $helper->getLoginUrl(FB_REDIRECT_URL, $permissions);
    
    // Render Facebook login button
    $login-button = '<a href="'.htmlspecialchars($loginURL).'">
	<img src="images/fb-login-btn.png"></a>';
}
?>

<!DOCTYPE html>
<html lang="en-US">
<head>
<title>Login with Facebook using PHP by Coderglass.com</title>
<meta charset="utf-8">
</head>
<body>
<div class="container">
    <div class="fb-box">
        <!-- Display login button -->
        <?php echo $login-button; ?>
    </div>
</div>
</body>
</html>


home-page.php

We have stored the facebook information in Session. The Facebook account information (name, email, profile picture, and profile link) is displayed on the home-page.php

 <!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<center>
<?php 

session_start();

if(isset($_SESSION["userName"])){ 
    
     echo "<h1>You Facebook Details </h1>";
 
      echo  $_SESSION['userPic'];
      echo  $_SESSION['userId'];
      echo  $_SESSION['userFName'];
      echo  $_SESSION['userEmail'];
      echo  $_SESSION['logOUT'];
    
}else{
    
    header("index.php");
}

?>
</center>
</body>
</html>
   

logout.php

User can log out from their Facebook account when they click on Lougout
  • Remove token and user data from the SESSION.
  • Reset OAuth access token.
  • Destroy the entire session data.
  • Redirect the user to the homepage.
<?php
// Include configuration file
require_once 'config.php';

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

unset($_SESSION['userName']);

// Remove user data from session
unset($_SESSION['userData']);

// Redirect to the homepage
header("Location:index.php");
?>