Login With Facebook - Web SDKs


Login With Facebook PHP SDK 
Nowadays users are not interested in filling a big form to registration. Short registration process helps to get more subscribers for your website. Login with Facebook is a quick and powerful way to integrate registration and login system on the website. Facebook is a most popular social network and most of the users have a Facebook account. Facebook Login allow users to sign into your website using their Facebook account credentials without sign up on your website.
This tutorial will explain how you can implement user login and registration system with Facebook using PHP and store the user profile data into the MySQL database. We’ll use Facebook PHP SDK v5.0 with Facebook Graph API to build Facebook Login system with PHP and MySQL.
To get started with the latest version of Facebook SDK v5.0, 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 folders and files structure.
facebook-php-sdk/
Facebook SDK v5 for PHP
  • User.php
  • fbConfig.php
  • index.php
  • logout.php
  • images/
    • fblogin-btn.png

Facebook Apps Creation

To access Facebook API you need to create Facebook App and specify App ID & App Secret at the time of call Facebook API. Follow the step-by-step guide to creating and configure a Facebook App from the App Dashboard.
  • Go to the Facebook App Dashboard and log in with your Facebook account.
  • Create a new Facebook apps with your desired name (like WebLogin).
  • If you want to test Facebook login at the localhost server, then your App Domains should be localhost. Also, localhostdomain will only work, once you add platform. For add a platform click on Settings link from the left side menu panel » Click on the Add Platform button » Choose Website category » Enter site URL (http://localhost/facebook_login_with_php/).
  • Once you completed the above steps, your apps settings page would something like the below.
    Stackoverflowcode-facebook-apps-creation
  • Now click on Status & Review link from the left side menu panel and make your apps live. Contact email is required for enable the apps live option. If you have not added apps contact email earlier, go to the settings page and add email. Once you submit the contact email, you would be able to enable the apps live option.
  • Congratulation! your apps creation has completed.
Are you want to get a detailed guide on Facebook App creation? Go through this guide to creating a Facebook App and get App ID & App Secret.

Database Table Creation

To store the user information from the Facebook database, a table (users) need to be created in MySQL database. At first, create a database (like Stackoverflowcodeworld) and run the below SQL on the database. The following SQL creates a users table with some basic fields in the database to hold the Facebook profile information.
CREATE TABLE `users` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `oauth_provider` enum('','facebook','google','twitter') COLLATE utf8_unicode_ci NOT NULL,
 `oauth_uid` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
 `first_name` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
 `last_name` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
 `email` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
 `gender` varchar(10) COLLATE utf8_unicode_ci NOT NULL,
 `locale` varchar(10) COLLATE utf8_unicode_ci NOT NULL,
 `picture` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `link` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `created` datetime NOT NULL,
 `modified` datetime NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Facebook SDK for PHP v5.0

The facebook-php-sdk/ directory contains the latest version (v5) of Facebook SDK for PHP. You don’t need to download it separately, Facebook SDK v5 is included in our source code.

User Class (User.php)

The User class helps to insert or update user data to the database using PHP and MySQL. In User.php file, you only need to specify your MySQL database credentials ($dbHost$dbUsername$dbPassword, and $dbName) and table name ($userTbl) where you want to store the user’s Facebook profile information.
<?phpclass User {
    private $dbHost     "localhost";
    private $dbUsername "root";
    private $dbPassword "";
    private $dbName     "Stackoverflowcodeworld";
    private $userTbl    'users';
    
    function __construct(){
        if(!isset($this->db)){
            // Connect to the database
            $conn = new mysqli($this->dbHost$this->dbUsername$this->dbPassword$this->dbName);
            if($conn->connect_error){
                die("Failed to connect with MySQL: " $conn->connect_error);
            }else{
                $this->db $conn;
            }
        }
    }
    
    function checkUser($userData = array()){
        if(!empty($userData)){
            // Check whether user data already exists in database
            $prevQuery "SELECT * FROM ".$this->userTbl." WHERE oauth_provider = '".$userData['oauth_provider']."' AND oauth_uid = '".$userData['oauth_uid']."'";
            $prevResult $this->db->query($prevQuery);
            if($prevResult->num_rows 0){
                // Update user data if already exists
                $query "UPDATE ".$this->userTbl." SET first_name = '".$userData['first_name']."', last_name = '".$userData['last_name']."', email = '".$userData['email']."', gender = '".$userData['gender']."', locale = '".$userData['locale']."', picture = '".$userData['picture']."', link = '".$userData['link']."', modified = '".date("Y-m-d H:i:s")."' WHERE oauth_provider = '".$userData['oauth_provider']."' AND oauth_uid = '".$userData['oauth_uid']."'";
                $update $this->db->query($query);
            }else{
                // Insert user data
                $query "INSERT INTO ".$this->userTbl." SET oauth_provider = '".$userData['oauth_provider']."', oauth_uid = '".$userData['oauth_uid']."', first_name = '".$userData['first_name']."', last_name = '".$userData['last_name']."', email = '".$userData['email']."', gender = '".$userData['gender']."', locale = '".$userData['locale']."', picture = '".$userData['picture']."', link = '".$userData['link']."', created = '".date("Y-m-d H:i:s")."', modified = '".date("Y-m-d H:i:s")."'";
                $insert $this->db->query($query);
            }
            
            // Get user data from the database
            $result $this->db->query($prevQuery);
            $userData $result->fetch_assoc();
        }
        
        // Return user data
        return $userData;
    }
}?>

Facebook API Configuration (fbConfig.php)

In fbConfig.php file, define Facebook App ID ($appId), App Secret ($appSecret), Callback URL ($redirectURL), and Permissions ($fbPermissions) to connect with Facebook API and working with SDK.
<?php
if(!session_id()){
    session_start();
}
// Include the autoloader provided in the SDKrequire_once __DIR__ '/facebook-php-sdk/autoload.php';
// Include required librariesuse Facebook\Facebook;
use Facebook\Exceptions\FacebookResponseException;
use Facebook\Exceptions\FacebookSDKException;
/*
 * Configuration and setup Facebook SDK
 */$appId         'InsertAppID'//Facebook App ID$appSecret     'InsertAppSecret'//Facebook App Secret$redirectURL   'http://localhost/facebook_login_with_php/'//Callback URL$fbPermissions = array('email');  //Optional permissions
$fb = new Facebook(array(
    'app_id' => $appId,
    'app_secret' => $appSecret,
    'default_graph_version' => 'v2.2',
));
// Get redirect login helper$helper $fb->getRedirectLoginHelper();
// Try to get access tokentry {
    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 Apps settings page.

Login & Profile Information (index.php)

If the user already logged in with the Facebook account, the profile details would be displayed, otherwise, Facebook login button will appear.
<?php// Include FB config file && User classrequire_once 'fbConfig.php';
require_once 'User.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: ./');
    }
    
    // Getting user facebook profile info
    try {
        $profileRequest $fb->get('/me?fields=name,first_name,last_name,email,link,gender,locale,picture');
        $fbUserProfile $profileRequest->getGraphNode()->asArray();
    } 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;
    }
    
    // Initialize User class
    $user = new User();
    
    // Insert or update user data to the database
    $fbUserData = array(
        'oauth_provider'=> 'facebook',
        'oauth_uid'     => $fbUserProfile['id'],
        'first_name'    => $fbUserProfile['first_name'],
        'last_name'     => $fbUserProfile['last_name'],
        'email'         => $fbUserProfile['email'],
        'gender'        => $fbUserProfile['gender'],
        'locale'        => $fbUserProfile['locale'],
        'picture'       => $fbUserProfile['picture']['url'],
        'link'          => $fbUserProfile['link']
    );
    $userData $user->checkUser($fbUserData);
    
    // Put user data into session
    $_SESSION['userData'] = $userData;
    
    // Get logout url
    $logoutURL $helper->getLogoutUrl($accessToken$redirectURL.'logout.php');
    
    // Render facebook profile data
    if(!empty($userData)){
        $output  '<h1>Facebook Profile Details </h1>';
        $output .= '<img src="'.$userData['picture'].'">';
        $output .= '<br/>Facebook ID : ' $userData['oauth_uid'];
        $output .= '<br/>Name : ' $userData['first_name'].' '.$userData['last_name'];
        $output .= '<br/>Email : ' $userData['email'];
        $output .= '<br/>Gender : ' $userData['gender'];
        $output .= '<br/>Locale : ' $userData['locale'];
        $output .= '<br/>Logged in with : Facebook';
        $output .= '<br/><a href="'.$userData['link'].'" target="_blank">Click to Visit Facebook Page</a>';
        $output .= '<br/>Logout from <a href="'.$logoutURL.'">Facebook</a>'; 
    }else{
        $output '<h3 style="color:red">Some problem occurred, please try again.</h3>';
    }
    
}else{
    // Get login url
    $loginURL $helper->getLoginUrl($redirectURL$fbPermissions);
    
    // Render facebook login button
    $output '<a href="'.htmlspecialchars($loginURL).'"><img src="images/fblogin-btn.png"></a>';
}?>
<html>
<head>
<title>Login with Facebook using PHP by stackoverflowcode.blogspot.com</title>
<style type="text/css">
    h1{font-family:Arial, Helvetica, sans-serif;color:#999999;}
</style>
</head>
<body>
    <!-- Display login button / Facebook profile information -->
    <div><?php echo $output?></div>
</body>
</html>

Logout (logout.php)

When the user wishes to logout from their account, the logout.php file will be loaded after logout from Facebook account.
<?php// Include FB config filerequire_once 'fbConfig.php';
// Remove access token from sessionunset($_SESSION['facebook_access_token']);
// Remove user data from sessionunset($_SESSION['userData']);

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

 Conclusion

In this tutorial, we’ve tried to make Facebook Login implementation quicker and easier. Using our script, you don’t need to any SDK or API 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. If you have any query or suggestions about this tutorial and scripts, feel free to comment here.
Note: If you want whole code follow me and leave a comment i will provide code package to   you thank you

Comments