Facebook OAuth Login Integration in PHP

Nowadays the web users are not interested in filling out a big form for registration on the website. The short registration process helps to get more subscribers to your website. Login with Facebook is a quick and powerful way to integrate registration and login system on the website. Facebook is the most popular social network, and most of the users have a Facebook account. Facebook Login allows users to sign in to your website using their Facebook account credentials without signing up on your website.

PHP SDK allows accessing the Facebook API from the web application. You can easily implement the Login with Facebook account using Facebook SDK for PHP. This tutorial will show how you can implement user login and registration system with Facebook using PHP and store the user profile data into the MySQL database. Our example Facebook Login script uses Facebook PHP SDK v5 with Facebook Graph API to build Facebook Login system with PHP and MySQL.

To get started with the latest version of Facebook SDK v5.x, make sure your system meets the following requirements.

  • PHP version should be 5.4 or greater.
  • The mbstring extension should be enabled.

Before you begin to integrate Login with Facebook using PHP, take a look at the file structure.

facebook_login_with_php/
├── config.php
├── dbConnect.php
├── index.php
├── logout.php
├── facebook-graph-sdk/
├── images/
│   ├── fb-login-btn.png
└── css/
    └── style.css

Create Facebook App

To access Facebook API you need to create a Facebook App and specify the App ID & App Secret at the time of calling the Facebook API. Follow the step-by-step guide to create Facebook App and generate App ID & Secret in the Meta apps dashboard.

Note that: The App ID and App secret need to be specified in the script at the time of Facebook API call. Also, the Valid OAuth Redirect URIs must be matched with the Redirect URL that specified in the script.

Create Database Table

To store the user’s profile information from Facebook, a table needs to be created in the database. The following SQL creates a users table with some basic fields in the MySQL database to hold the Facebook account information.

CREATE TABLE `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `oauth_provider` varchar(50) DEFAULT NULL COMMENT 'FACEBOOK/GOOGLE/X/LINKEDIN',
  `oauth_uid` varchar(100) DEFAULT NULL,
  `first_name` varchar(25) DEFAULT NULL,
  `last_name` varchar(25) DEFAULT NULL,
  `email` varchar(50) DEFAULT NULL,
  `picture` varchar(255) DEFAULT NULL,
  `created` datetime NOT NULL DEFAULT current_timestamp(),
  `modified` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Facebook SDK for PHP

The PHP SDK library allows you to access the Facebook Platform service from a PHP web application. In this example script, the facebook-graph-sdk directory contains the latest version (v5) of the Facebook SDK for PHP.
Note that: You don’t need to download it separately, all the required files of Facebook PHP SDK v5 are included in our Facebook Login PHP source code.

Facebook API and Database Configuration (config.php)

In the config.php file, constant variables of the Facebook API and database settings are defined.
Facebook API Constants:

  • FB_APP_ID – Specify the Facebook App ID.
  • FB_APP_SECRET – Specify the Facebook App Secret.
  • FB_REDIRECT_URL – Specify the Callback URL.

Database Constants:

  • DB_HOST – Specify the database host.
  • DB_USERNAME – Specify the database username.
  • DB_PASSWORD – Specify the database password.
  • DB_NAME – Specify the database name.

Call Facebook API:

  • The PHP SDK library is used to connect with Facebook API and working with OAuth client.
<?php 

// Facebook API configuration
define('FB_APP_ID''_Facebook_App_ID_HERE_');
define('FB_APP_SECRET''_Facebook_App_Secret_HERE_'); 
define('FB_REDIRECT_URL''_Callback_URL_HERE_');

// Database configuration
define('DB_HOST''localhost');
define('DB_USERNAME''root');
define('DB_PASSWORD''root');
define('DB_NAME''codexworld_db');

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

// Include the autoloader provided in the SDK
require_once __DIR__ '/facebook-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;
}

?>

Note that: You’ll find the App ID and App Secret on your Facebook App settings page.

Database Connection (dbConnect.php)

The dbConnect.php file is used to connect the database using PHP and MySQL.

<?php  

// Connect with the database 
$db = new mysqli(DB_HOSTDB_USERNAMEDB_PASSWORDDB_NAME); 
 
// Display error if failed to connect 
if ($db->connect_errno) { 
    
printf("Connect failed: %s\n"$db->connect_error); 
    exit(); 
}

?>

Facebook Authentication and Process Account Data (index.php)

In the index.php file, the Facebook API authentication process is handled using PHP.

  • Initially, the authentication URL is generated using the getLoginUrl() method of the login helper class, and the Facebook Sign-in button is displayed on the web page.
  • If the user authenticates with their Facebook account, the following happens:
    • The profile information is retrieved from the Facebook account using the Facebook Graph API.
    • The Facebook profile data is inserted into the database using MySQL Prepared Statements.
    • The Facebook profile details (Name, First name, Last name, Email, and Picture) are displayed on the webpage.
    • Also, the Logout link is generated using getLogoutUrl() method of the login helper class.
<?php 
// Include configuration file
require_once 'dbConnect.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
        
$longLivedAccessToken $oAuth2Client->getLongLivedAccessToken($_SESSION['facebook_access_token']);
        
$_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: ./");
        exit;
    }
    
    
// Getting user's profile info from Facebook
    
try {
        
$graphResponse $fb->get('/me?fields=name,first_name,last_name,email,picture');
        
$fb_user $graphResponse->getGraphUser();
    } catch(
FacebookResponseException $e) {
        
$fb_api_error 'Graph returned an error: ' $e->getMessage();
    } catch(
FacebookSDKException $e) {
        
$fb_api_error 'Facebook SDK returned an error: ' $e->getMessage();
    }

    if(!empty(
$_SESSION['fb_api_error'])){
        
// Remove existing data from session
        
session_destroy();

        
// Store error message in session
        
$_SESSION['fb_api_error'] = $fb_api_error;

        
// Rediect to the login page
        
header("Location: ./");
        exit;
    }

    if(!empty(
$fb_user)){
        
// Hold user profile data in array
        
$userData = array(
            
'oauth_uid'  => !empty($fb_user['id'])?$fb_user['id']:'',
            
'first_name' => !empty($fb_user['first_name'])?$fb_user['first_name']:'',
            
'last_name'  => !empty($fb_user['last_name'])?$fb_user['last_name']:'',
            
'email'      => !empty($fb_user['email'])?$fb_user['email']:'',
            
'picture'    => !empty($fb_user['picture']['url'])?$fb_user['picture']['url']:''
        
);

        
// Check whether the user already exists in the database
        
$stmt $db->prepare("SELECT id FROM users WHERE oauth_uid = ?");
        
$stmt->bind_param("s"$userData['oauth_uid']);
        
$stmt->execute();
        
$stmt->store_result();
        
//$stmt->close();

        
if($stmt->num_rows 0){
            
$stmt->bind_result($user_id);
            
$stmt->fetch();

            
// Update user data in the database
            
$sqlQ "UPDATE users SET first_name=?, last_name=?, email=?, picture=?, modified=NOW() WHERE id=?"
            
$stmt $db->prepare($sqlQ); 
            
$stmt->bind_param("ssssi"$userData['first_name'], $userData['last_name'], $userData['email'], $userData['picture'], $user_id);
            
$update $stmt->execute(); 
        }else{
            
$oauth_provider 'FACEBOOK';

            
// Insert user data in the database
            
$sqlQ "INSERT INTO users (oauth_provider,oauth_uid,first_name,last_name,email,picture,created,modified) VALUES (?,?,?,?,?,?,NOW(),NOW())"
            
$stmt $db->prepare($sqlQ); 
            
$stmt->bind_param("ssssss"$oauth_provider$userData['oauth_uid'], $userData['first_name'], $userData['last_name'], $userData['email'], $userData['picture']); 
            
$insert $stmt->execute(); 
        }

    }
    
    
// Get logout url
    
$file_info pathinfo(FB_REDIRECT_URL);
    
$BASE_RURL = isset($file_info['extension']) ? str_replace($file_info['filename'] . "." $file_info['extension'], ""FB_REDIRECT_URL) : FB_REDIRECT_URL;
    
//$logoutURL = $helper->getLogoutUrl($accessToken, $BASE_RURL.'logout.php');
    
$logoutURL $BASE_RURL.'logout.php';
}else{
    
// Get login url
    
$permissions = ['email']; // Optional permissions
    
$loginURL $helper->getLoginUrl(FB_REDIRECT_URL$permissions);
}

// Get error from session
$fb_api_error '';
if(!empty(
$_SESSION['fb_api_error'])){
    
$fb_api_error $_SESSION['fb_api_error'];
    unset(
$_SESSION['fb_api_error']);
}
?> <?php if(!empty($loginURL)){ ?> <div class="profile-info"> <!-- Render Facebook login button --> <a href="<?php echo htmlspecialchars($loginURL); ?>"> <img src="images/fb-login-btn.png" width="320"> </a> </div> <?php }elseif(!empty($userData)){ ?> <!-- Display Facebook profile information --> <div class="profile-container"> <img src="<?php echo !empty($userData['picture'])?$userData['picture']:'images/user.png'?>"> </div> <div class="profile-info"> <h1><?php echo $userData['first_name'].' '.$userData['last_name']; ?></h1> <p class="job-title"><?php echo $userData['email']; ?></p> <p class="desc">Profile ID: <span><?php echo $userData['oauth_uid']; ?></span></p> </div> <div class="profile-social"> <a href="<?php echo $logoutURL?>" class="btn btn-primary">Logout</a> </div> <div class="card-bottom"></div> <?php }else{ ?> <div class="alert alert-danger"> <?php echo !empty($fb_api_error)?$fb_api_error:'Oops! Something went wrong. Please try again later.'?> <a href="index.php">Start Over</a> </div> <?php ?>

Logout (logout.php)

If the user wishes to log out from their Facebook account, the logout.php file is loaded.

  • Remove access token and user data from the SESSION.
  • Redirect the user to the homepage.
<?php

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

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

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

?>

Login with Facebook using JavaScript

Conclusion

In this tutorial, we’ve tried to make Facebook Login implementation quicker and easier. The example code integrates Facebook Login with the Facebook SDK for PHP. You don’t need to add the SDK library files separately, our source code contains all the required files with the SDK v5 for PHP. You only need to specify some minimal settings for adding login system with Facebook to your website using PHP. To make the Facebook login more user-friendly, you can use JavaScript SDK to integrate Facebook Login without page refresh using JavaScript.

Looking for expert assistance to implement or extend this script’s functionality? Submit a Service Request

196 Comments

  1. Raman Baghla Said...
  2. Raman Baghla Said...
    • CodexWorld Said...
  3. Santosh Kamble Said...
  4. John Wood Said...
    • CodexWorld Said...
  5. Paul Kelleher Said...
  6. Mahendra Said...
    • CodexWorld Said...
  7. Nana Partykar Said...
  8. Suraj Said...
  9. Manish Said...
  10. Abhishek Kr Said...
  11. Parag Said...
  12. Raja Said...
  13. Rajiv Said...
    • CodexWorld Said...
  14. Rajiv Said...
    • CodexWorld Said...
  15. Mil Said...
  16. Minimal Said...
  17. Atis Said...
  18. Neosoft Said...
  19. Andy Said...
  20. Abdul Majeed Said...
  21. Shweta Said...
    • CodexWorld Said...
  22. Frank Legas Said...
  23. Anupam Said...
  24. Baser Said...
  25. Alessandro Said...
  26. Ankur Said...
  27. Irshad Khan Said...
  28. Mitali Said...
    • CodexWorld Said...
  29. Anurag Said...
    • CodexWorld Said...
  30. ZANZI Said...
  31. Danish Said...
  32. Buxxy Said...
  33. Pramod Khandalkar Said...
  34. Jack Said...
  35. Muraly Said...
  36. Pavan Maganti Said...
  37. Amit Kumar Said...
  38. Rahul Yadav Said...
  39. Gihantwister Said...
    • CodexWorld Said...
  40. Developer Said...

Leave a reply

construction Need this implemented in your project? Request Implementation Help → keyboard_double_arrow_up