Login with Facebook using PHP

Login or Resister user using Facebook

Login with Facebook using PHP

Hmm, If your website has a customer base section or any kind of customer interaction activity, then you must need to add login with Facebook. In this tutorial, I'll show you a complete step by step process to implement login with Facebook using PHP.

Mostly user irritates to fill the lengthy registration form, as well as nowadays user, don't want to fill the username and password every time to login into the website. So that, to avoid every irritation process for your valuable user/customer, simply add Facebook SDK into your website.

You can use the Facebook SDK for much more things. But I am going to show you Facebook SDK implementation for login or signup process. You can register your user with respective profile data or you can simply log in.

So, Let's start with these simple steps to integrate login with Facebook using PHP.

Create a Facebook App

To get any kind of Facebook profile or page information you must need to create your app in the Facebook Developer section. Each App has an App ID & App Secret. There are a few simple steps to create your Facebook App. Follow these steps:

Go to the Facebook developer page

First of all, simply go to the Facebook for Developers page and log in with your Facebook account. You can simply log in with your username and password. You can also create a different account for that.

Create your App

After login into your facebook developer page, you'll see a dashboard of developer page. Now, click the My Apps link at the top navigation bar and select Add New App. When you click on it, you'll get a popup box like this.

facebook-create-app
facebook-create-app

In the above box fill your App name. You can change your contact email if you don't want to continue with existing email id.

App basic settings

Now, you need to go Basic page section into the Settings. This is the location where you'll get your App ID & App Secret for your APP. Simply copy App ID & App Secret and paste into your PHP file.

facebook-app-setting
facebook-app-setting

In this screen, you will get an option to add your App icon or you can say your App logo with given respective sizes. You will able to add your domain name as well as your App category also.

When you want to go live with this App, you need to add the privacy policy link of your website into the given field of basic setting section. After completing your information click on save changes to apply your changes.

Add a Product

Next steps are very important. In this step, you will add your product for whatever you want to do with your App. Basically you can add more than one product to your Facebook App. But this time I am going to add only Facebook login product into the newly created App.

As you can see the above image, Simply click on the Plus (+) icon of the sidebar of the Dashboard to add your product into your App. After hinting a click you will get another screen just like this.

I the above screen, look at the Facebook login section and just simply click on the Set Up button to continue. Now, you will get another screen to ask for your login platform to add to your Facebook App.

Now, choose your platform as a web. After clicking on the web, your Facebook App setup is almost done for your login with Facebook using PHP

Facebook SDK for PHP

In the next step, we will move to the development section of the website. Now, you need to add Facebook SDK for your PHP setup. Because without Facebook SDK you can't perform any task related to Facebook.

To get started with the Facebook SDK for PHP, see the PHP-graph-SDK example on GitHub. The latest version of the Facebook SDK for PHP (v5).

Facebook SDK via Composer

The quick and very simple step is to add Facebook SDK via Composer. Just run a composer command into your working folder via command line to add Facebook SDK very quickly.

composer require facebook/graph-sdk

When you'll execute this command into your command line, Facebook SDK vendor folder downloaded to your project. You can look at the image below.

Now, we are done the first two-step to create login with Facebook using PHP. Let's move to the PHP file works.

API Configuration

You just need to create a config file to store all the credentials of your Facebook login API. In the above file, you will define your APP required information like FB_APP_ID, FB_APP_SECRET, and FB_REDIRECT_URL.

Facebook API Constants

  • FB_APP_ID => You will get from Facebook App Settings->basic
  • FB_APP_SECRET => You will get from Facebook App Settings->basic
  • FB_REDIRECT_URL => Your website call back URL

Configuration file

Your configuration file just like this. Simply replace your Facebook App ID, Facebook App secret and Facebook callback URL.

<?php
session_start();

/*
 * Basic Site Settings and API Configuration
 */

// Facebook API configuration
define('FB_APP_ID', 'APP_ID');
define('FB_APP_SECRET', 'APP_SECRET');
define('FB_REDIRECT_URL', 'CALLBACK_URL');

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

$fb = new Facebook\Facebook([
  'app_id' => FB_APP_ID, // Replace {app-id} with your app id
  'app_secret' => FB_APP_SECRET,
  'default_graph_version' => 'v3.2',
  ]);

$helper = $fb->getRedirectLoginHelper();

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

Log in/Sign up with Facebook

In your login page, you require to add your config file at the top of the section. This is the file where all communication between the user, website, and Facebook will be performed. All the Facebook API authentication process is handled using by this PHP file. This file should be your login file.

First of all, you will check if the access token is present in the session, simply set the Default Access Token to the Facebook SDK object. otherwise OAuth 2.0 client handler helps to manage access tokens.

After exchanges, a short-lived access token for a long-lived one, set default access token to be used in the script.

<?php 
require_once('config.php');

if(isset($accessToken)){
    if(isset($_SESSION['fb_access_token'])){
		 // Set default access token to be used in script
        $fb->setDefaultAccessToken($_SESSION['fb_access_token']);
    }else{
        // Put short-lived access token in session
        $_SESSION['fb_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['fb_access_token']);
        $_SESSION['fb_access_token'] = (string) $longLivedAccessToken;
        
        // Set default access token to be used in script
        $fb->setDefaultAccessToken($_SESSION['fb_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 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['gender']     = !empty($fbUser['gender'])?$fbUser['gender']:'';
    $fbUserData['picture']    = !empty($fbUser['picture']['url'])?$fbUser['picture']['url']:'';
    $fbUserData['link']       = !empty($fbUser['link'])?$fbUser['link']:'';
    
    // Get logout url
    $logoutURL = $helper->getLogoutUrl($accessToken, FB_REDIRECT_URL.'logout.php');
    
    // Render Facebook profile data
    if(!empty($fbUserData)){
        $output  = '<h2>User Facebook Profile Details</h2>';
        $output .= '<div>';
        $output .= '<img src="'.$fbUserData['picture'].'"/>';
        $output .= '<p><b>Facebook ID:</b> '.$fbUserData['oauth_uid'].'</p>';
        $output .= '<p><b>Name:</b> '.$fbUserData['first_name'].' '.$fbUserData['last_name'].'</p>';
        $output .= '<p><b>Email:</b> '.$fbUserData['email'].'</p>';
        $output .= '<p><b>Gender:</b> '.$fbUserData['gender'].'</p>';
        $output .= '<p><b>Profile Link:</b> <a href="'.$fbUserData['link'].'" target="_blank">Click to visit Facebook page</a></p>';
        $output .= '<p><b>Logout from <a href="'.$logoutURL.'">Facebook</a></p>';
        $output .= '</div>';
    }else{
        $output = '<h2 style="color:red">Something went wrong, please try again.</h2>';
    }
}else{
    // Get login url
    $permissions = ['email']; // Optional permissions
    $loginURL = $helper->getLoginUrl(FB_REDIRECT_URL, $permissions);
    
    // Render Facebook login button
    $login = '<a href="' . htmlspecialchars($loginURL) . '"><button class="btn-success">Log in with Facebook!</button></a>';
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <title>Facebook Login Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>

<div class="container">
	<div class="text-center">
	  <h1>Facebook Login Example</h1>
	  <?php
	  if(isset($login)) echo $login;
	  ?>
	</div>
	<div>
	  <?php
	  if(isset($output)) echo $output;
	  ?>
	</div>
</div>

</body>
</html>

Store User Data

Simply, either you can just Log in with the user Facebook account or you can Register this user for future prospective. For registering the user you can use your Database to store all respective information of the user.

You can use $fbUserData array to get all the information of the user.

Logout with Facebook

Basically, logout performs in two ways. First is, if you want to log out user only from your website then simply just follow two things.

  • Remove access token and user data from your website SESSION.
  • Re-direct to your continue webpage.

Second options are If you want to log out from your website as well as Facebook also then you need to follow this step.

  • Get logout URL from $helper->getLogoutUrl.
  • Log out from Facebook.
  • Remove access token and user data from your website SESSION.
  • Re-direct to your continue webpage.
<?php 
require_once('config.php');

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

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

Conclusion

In this tutorial, we've discussed social login with Facebook using PHP. This one very powerfull medium to catch your user into your website. This helps very much to fast login and register feature.

By using this Facebook SDK you can log in/Resister user quickly with the help of Facebook SDK v5 for PHP. If you want to download the script then click on below link to download it.

Download Login with Facebook using PHP

Top