Login with Facebook using PHP SDK

Login with Facebook using PHP SDK - Tuts Make

Facebook login example is very common and easy to use. Nowadays most of the users do not want to fill long registration forms on websites. That is why most of the developers provide a facebook login button on their websites.

If the user has a facebook account they can log in to the website with FB account. PHP is a very powerful language and Facebook also provides PHP SDK to access facebook API.

File Structure and facebook PHP SDK Class

Before starting further, you need to understand the file structure. Create bellow listed files and download facebook PHP SDK class form here.

  • index.php
  • welcome.php
  • fb-callback.php
  • fb-config.php
  • logout.php


Create an app on Facebook

To create a facebook login button you need to do the following steps. So, The below image explains the menu of the app dashboard.

Step 1 – Create a Facebook App

First of all, you have to make an app in the Facebook Developer Console.

Because when you create an app in the Facebook Developer Console. Then Facebook provides you some secret details. With the help of which you can integrate and implement Facebook login in node js app.

If you do not know how to make apps on Facebook Developer Console. So you can make an app in the Facebook Developer Console by following the steps given below:

Step 1 – Visit the following url https://developers.facebook.com/apps/ and create a new facebook app.

Step 2 – Create facebook app with email and app name look like below picture:

  1. Create an app on facebook. (Click here to create FB App)
  2. After creating the app you need to add a product on the app dashboard that defines the app scope select Facebook Login.
  3. In the app, the dashboard goes to the settings there are two menus BasicAdvanced.
  4. Finally, you need to set the callback URL into the app go to the product->settings and enter you a callback URL and save changes.
  5. Probably you need to change the status of your app to live

Furthermore, the below image shows where you set the callback URL. And remember Client and Web OAuth login must be enabled.

After setting up the app follow the below process to create a login button. Into the basic settings of your app, you will see the App ID and App Secret copy these ids and replace them in the fb-config.php file as below.

<?php
session_start();
include_once('php-graph-sdk-5.x/src/Facebook/autoload.php');
$fb = new Facebook\Facebook(array(
    'app_id' => '{app-id}', // Replace with your app id
    'app_secret' => '{app-secret}',  // Replace with your app secret
    'default_graph_version' => 'v3.2',
));
 
$helper = $fb->getRedirectLoginHelper();
?>

Remember: you must need to include this file into all files at the top of the page. Without this file, you are not able to access FB PHP SDK.

Now in the index.php, you need to paste below code just after the fb-config.php includes. The below code snippet creates a Login URL with email permission. This example is in bootstrap4 you can use URL on structure.

<?php
$permissions = array('email'); // Optional permissions
$loginUrl = $helper->getLoginUrl('<a class="vglnk" href="https://CodeOne.com/demo/php/login-with-facebook-using-php-sdk/fb-callback.php" rel="nofollow"><span>https</span><span>://</span><span>learncodeweb</span><span>.</span><span>com</span><span>/</span><span>demo</span><span>/</span><span>php</span><span>/</span><span>login</span><span>-</span><span>with</span><span>-</span><span>facebook</span><span>-</span><span>using</span><span>-</span><span>php</span><span>-</span><span>sdk</span><span>/</span><span>fb</span><span>-</span><span>callback</span><span>.</span><span>php</span></a>', $permissions);
?>

<form method="post">
    <div class="form-group">
        <label>Login ID</label>
        <input type="text" class="form-control" name="userId" placeholder="User ID">
    </div>
    <div class="form-group">
        <label>Password</label>
        <input type="password" class="form-control" name="userPassword" placeholder="User Password">
    </div>
    <div class="form-group">
        <button type="button" class="btn btn-danger btn-block" value="Login"><i class="fa fa-sign-in-alt"></i> Login</button>
    </div>
    <div class="form-group">
        <a href="<?php echo htmlspecialchars($loginUrl); ?>" class="btn btn-primary btn-block"><i class="fab fa-facebook-square"></i> Log in with Facebook!</a>
    </div>
</form>

Now on the callback page, we check the user and set session if the user has an account on Facebook. Open the fb-callback.php page and paste the below code in it.

<?php
include_once('fb-config.php');
 
try {
  $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 ($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';
  }
  exit;
}
 
if(!$accessToken->isLongLived()){
  // Exchanges a short-lived access token for a long-lived one
  try {
    $accessToken = $oAuth2Client->getLongLivedAccessToken($accessToken);
  } catch (Facebook\Exceptions\FacebookSDKException $e) {
    echo "<p>Error getting long-lived access token: " . $e->getMessage() . "</p>\n\n";
    exit;
  }
}
 
//$fb->setDefaultAccessToken($accessToken);
 
# These will fall back to the default access token
$res    =   $fb->get('/me',$accessToken->getValue());
$fbUser =   $res->getDecodedBody();
 
 
$resImg     =   $fb->get('/me/picture?type=large&redirect=false',$accessToken->getValue());
$picture    =   $resImg->getGraphObject();
 
 
$_SESSION['fbUserId']       =   $fbUser['id'];
$_SESSION['fbUserName']     =   $fbUser['name'];
$_SESSION['fbAccessToken']  =   $accessToken->getValue();
 
header('Location: welcome.php');
exit;
?>

On the welcome page, you can access the login user data with the help of $_SESSION.

If you want to logout the user from everywhere I mean of FB then you need to use the below code. Because of the below code user will logout from the FB and on logout.php page you unset the FB sessions that your start on callback page. Or if you do not want to logout the user form FB you just sent the user to logout.php where you unset the FB sessions.

$logoutUrl = $helper->getLogoutUrl($_SESSION['fbAccessToken'], '<a class="vglnk" href="https://CodeOne.com/demo/php/login-with-facebook-using-php-sdk/logout.php" rel="nofollow"><span>https</span><span>://</span><span>learncodeweb</span><span>.</span><span>com</span><span>/</span><span>demo</span><span>/</span><span>php</span><span>/</span><span>login</span><span>-</span><span>with</span><span>-</span><span>facebook</span><span>-</span><span>using</span><span>-</span><span>php</span><span>-</span><span>sdk</span><span>/</span><span>logout</span><span>.</span><span>php</span></a>');
echo '<a href="'.$logoutUrl.'" class="btn btn-lg btn-danger"><i class="fa fa-fw fa-power-off"></i> Logout</a>';
Open the logout.php page and paste the below code to unset the session.
<?php
include_once('fb-config.php');
session_destroy();
unset($_SESSION['fbUserId']);
unset($_SESSION['fbUserName']);
unset($_SESSION['fbAccessToken']);
header('location: <a class="vglnk" href="https://CodeOne.com/demo/php/login-with-facebook-using-php-sdk/index.php" rel="nofollow"><span>https</span><span>://</span><span>learncodeweb</span><span>.</span><span>com</span><span>/</span><span>demo</span><span>/</span><span>php</span><span>/</span><span>login</span><span>-</span><span>with</span><span>-</span><span>facebook</span><span>-</span><span>using</span><span>-</span><span>php</span><span>-</span><span>sdk</span><span>/</span><span>index</span><span>.</span><span>php</span></a>');
exit;
?>

Leave a Reply

Your email address will not be published.