Facebook Login using PHP SDK

  • Tech Area
  • January 25, 2024



Nowadays Facebook login is very common on website and easy to use. Most of the website users do not want to fill long registration forms details. So most of the developers provide a Facebook login button on their websites.

If the user has a Facebook account and don’t want to fill long details then they can log in to the website with own Facebook account. Facebook provides PHP SDK to access Facebook API. We can easily integrate to the website.

File Structure with Facebook PHP SDK Class

PHP SDK Installation

The Facebook PHP SDK can be installed with Composer. Run this command:

composer require facebook/graph-sdk

Below are the step by step process of how to create an app on Facebook.

Step 1: Create an App on Facebook

To create an App on FB simply go to https://developers.facebook.com/ and click on Create App

Step 2: Add products to your app

After creating the app you need to add a product on the app dashboard. Below are the screenshot of all product. select Facebook Login

Now, select the platform for the app.

Now, enter your live site URL.

Now, you need to set the Valid OAuth Redirect URIs into the app go to the Facebook Login->settings and enter redirect_uri and save changes.

Now, you need go to the App settings->Basic and enter the required details and save changes.

Now, you need to change the status of your app to Live.

Step 3: Create index.php file

index.php

<html>  
<head>  
    <title>Facebook Login Form</title>  
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" /> 
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css" integrity="sha384-UHRtZLI+pbxtHCWp1t77Bi1L4ZtiqrqD80Kn4Z8NTSRyMA2Fd33n5dQ8lWUE00s/" crossorigin="anonymous"> 
</head>
<style>
 .box
 {
  width:100%;
  max-width:400px;
  background-color:#f9f9f9;
  border:1px solid #ccc;
  border-radius:5px;
  padding:16px;
  margin:0 auto;
 }
</style>
<body> 
<?php
session_start();
require_once 'vendor/autoload.php';

$fb = new Facebook\Facebook([
'app_id' => '', // your app id
'app_secret' => '', // your app secret
'default_graph_version' => 'v2.4',
]);

$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');
$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='https://graph.facebook.com/$fbid/picture?redirect=true'>";
# save the user information 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 {
	?>
    <div class="container">  
    <div class="table-responsive">  
    <h3 align="center">Login using Facebook in PHP</h3>
     <div class="box">
      <div class="form-group">
       <label for="email">Emailid</label>
       <input type="text" name="email" id="email" placeholder="Enter Email" class="form-control" required />
      </div>
      <div class="form-group">
       <label for="password">Password</label>
       <input type="password" name="pwd" id="pwd" placeholder="Enter Password" class="form-control"/>
      </div>
      <div class="form-group">
       <input type="submit" id="login" name="login" value="Login" class="btn btn-success form-control"/>
       <hr>
       <?php
       $loginUrl = $helper->getLoginUrl('https://rename-online.com/facebook-login-using-php/', $permissions);
       ?>
       <center><a href="<?php echo $loginUrl; ?>" class="btn btn-primary btn-block"><i class="fab fa-facebook-square"></i> Log in with Facebook!</a></center>
      </div>
      </div>
   </div>  
  </div>
<?php } ?>
</body>  
</html>

Step 4: Create profile.php file

profile.php

<?php
session_start();
?>
<head>
<title>Login using Facebook in PHP</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
</head>
<style>
 .box
 {
  width:100%;
  max-width:400px;
  background-color:#f9f9f9;
  border:1px solid #ccc;
  border-radius:5px;
  padding:16px;
  margin:0 auto;
 }
</style>
<body>     
<?php if($_SESSION['fb_id']) {?>
<div class="container">  
    <div class="table-responsive">  
     <div class="box">
   <center><?php echo $_SESSION['fb_pic']?></center>
  <div class="card-body">
    <h4 class="card-title"><?php echo $_SESSION['fb_name']; ?></h4>
    <p class="card-text"><?php echo  $_SESSION['fb_id']; ?></p>
	    <p class="card-text"><?php echo $_SESSION['fb_email']; ?></p>
    <a href="https://rename-online.com/facebook-login-using-php/logout.php" class="btn btn-primary">Logout</a>
  </div>
</div>
</div>
</div>
<?php } ?>
</body>
</html>

Step 5: Create logout.php file

logout.php

<?php 
   session_start();
   session_unset();
   header("Location: index.php");        
?>

Download Source Code


Subscribe us via Email

Join 10,000+ subscriber

Subscribe on YouTube