AllsWeb Blog
No Result
View All Result
  • Home
  • Main Home
  • PHP and MySQL
  • JavaScript
    • jQuery & AJAX
  • WordPress
  • SEO
  • Web Hosting
  • Comparison
Support
Knowledgebase
  • Home
  • Main Home
  • PHP and MySQL
  • JavaScript
    • jQuery & AJAX
  • WordPress
  • SEO
  • Web Hosting
  • Comparison
No Result
View All Result
AllsWeb White Logo
No Result
View All Result
Home PHP and MySQL

Login with Facebook using PHP

Create a Facebook App

Lakshika Mathur by Lakshika Mathur
December 14, 2019
Reading Time: 10 mins read
0
Login with Facebook using PHP

Presently, the web users have less interest in filling a long-form for registration on the website. Therefore, the short registration process helps to get more subscribers to your site. Login with Facebook is a fast and powerful way to integrate registration and login system on the website. Facebook is the most renowned social networking site, and a lot of users have a Facebook account. Similarly, Facebook Login allows users to sign in to your site using their Facebook account information without sign up on your website.

The PHP SDK allows accessing the Facebook API from a web application. In addition, you can quickly implement login with a Facebook account using the Facebook SDK for PHP. This guide will show how you can apply the login and registration system with Facebook using PHP and also store the user profile data into the MySQL database. Our example Facebook Login script uses the Facebook PHP SDK v5 with Facebook Graph API to build a Facebook Login system with PHP and MySQL.

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

  • PHP version should be 5.4 or higher.
  • Enable Mastering extension 

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

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

Create a Facebook App

To use the Facebook API, you need to create a Facebook app and specify the App ID and App Secret. While creating the Facebook API. Follow the step by step guide to create a Facebook App and generate App ID and Secret in Facebook Developers Dashboard.

  1. Open the Facebook for Developers page and log in with your Facebook account.
  2. Now, Click on the My Apps link at the top navigation bar and select Add New App.
    • Firstly, Enter the Display Name and Contact Email.
    • Secondly, Click on the Create App ID button.
    • Now, You will be redirected to the App Dashboard.
  3. Go to the Settings » Basic page.
    • Specify the App Domains and click on the Category of your App.
    • Click Save Changes.
  4. Go to the Add a Product page by clicking the PRODUCTS(+) link at the left navigation menu panel.
    • Click on Facebook Login to Set Up.
    • Select the Web as the App platform.
    • Enter the Site URL and Save.
  5. Navigate to the Facebook Login » Settings page.
    • In the Valid OAuth Redirect URIs field, enter the Redirect URL.
    • Click Save Changes.

Go to Settings »Basic page, pay attention to App ID and App Secret. This App ID and App Secret allows you to use the Facebook API.

Create a Facebook App
Create a Facebook App

Note: Specify the App ID and App Secret in the script at the time of the Facebook API call. Besides, and match the Valid OAuth Redirect URIs with the Redirect URL that specified in the text.

Get the Profile Link and Gender

You must submit a request for user_link and user_gender permissions to retrieve the user’s Facebook timeline link and gender, 

  • Firstly, Go to the App Review » Permissions and Features page.
  • Secondly, request for user_link and user_gender permissions 
  • Now, Submit the information which is required.

Once the review process by Facebook is completed and approved; as a result, you will be able to get the user profile link and gender from the Facebook Profile API.

Create Database Table

To store the user’s profile information from Facebook, You need to create a table in the database. The following SQL creates a user table with some primary fields in the MySQL database to hold the Facebook account 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(50) COLLATE utf8_unicode_ci NOT NULL,
 `first_name` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
 `last_name` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
 `email` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
 `gender` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL,
 `picture` varchar(200) COLLATE utf8_unicode_ci NOT NULL,
 `link` varchar(100) 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

The facebook-php-graph-SDK / directory has the latest version (v5) of the Facebook SDK for PHP. You do not need to download it separately; Include all required files of Facebook PHP SDK v5 in our Facebook login PHP source code.

User Class (User.class.php)

The user class handles database related operations (connect, update, and insert) using PHP and MySQL. It helps to connect to the database and insert/update Facebook account data in the user’s table.

  • __construct() – Connect to the MySQL database.
  • checkUser() – Insert the user profile data based on the OAuth provider and ID. 
    <?php
    /*
     * User Class
     * This class is used for database related (connect, insert, and update) operations
     * @author    CodexWorld.com
     * @url        http://www.codexworld.com
     * @license    http://www.codexworld.com/license
     */
    class User {
        private $dbHost     = DB_HOST;
        private $dbUsername = DB_USERNAME;
        private $dbPassword = DB_PASSWORD;
        private $dbName     = DB_NAME;
        private $userTbl    = DB_USER_TBL;
        
        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']."', picture = '".$userData['picture']."', link = '".$userData['link']."', modified = NOW() 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']."', picture = '".$userData['picture']."', link = '".$userData['link']."', created = NOW(), modified = NOW()";
                    $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;
        }
    }

     

    Site Settings and API Configuration (config.php)

The database settings and Facebook API configuration constant variables are defined in the config.php file.

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.
  • DB_USER_TBL – Specify the table name where the user’s account data will be stored.

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.

Call Facebook API:

  • Use the PHP SDK library to connect with Facebook API and working with OAuth client.
<?php
/*
 * Basic Site Settings and API Configuration
 */

// Database configuration
define('DB_HOST', 'MySQL_Database_Host');
define('DB_USERNAME', 'MySQL_Database_Username');
define('DB_PASSWORD', 'MySQL_Database_Password');
define('DB_NAME', 'MySQL_Database_Name');
define('DB_USER_TBL', 'users');

// Facebook API configuration
define('FB_APP_ID', 'Insert_Facebook_App_ID');
define('FB_APP_SECRET', 'Insert_Facebook_App_Secret');
define('FB_REDIRECT_URL', 'Callback_URL');

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

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

 

Login & Get Facebook Account Data (index.php)

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

  • Generate the authentication URL using the getLoginUrl() method of a login helper class, and display the Facebook Sign-in button on the web page.
  • If the user authenticates with their Facebook account, the following things will happen:
    • Information on the profile can be retrieved from the Facebook account using Facebook Graph API.
    • You will be able to Insert the account data into the database using checkUser() function of User class.
    • You can store the user information in the SESSION.
    • The Facebook profile details (Name, Last name, First name, Email, Gender, Picture, and Profile link) display on the webpage.
    • The Logout link is generated using getLogoutUrl() method of the login helper class.
      <?php
      // Include configuration file
      require_once 'config.php';
      
      // Include User class
      require_once 'User.class.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'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;
          }
          
          // Initialize User class
          $user = new User();
          
          // 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']:'';
          
          // Insert or update user data to the database
          $fbUserData['oauth_provider'] = 'facebook';
          $userData = $user->checkUser($fbUserData);
          
          // Storing user data in the session
          $_SESSION['userData'] = $userData;
          
          // Get logout url
          $logoutURL = $helper->getLogoutUrl($accessToken, FB_REDIRECT_URL.'logout.php');
          
          // Render Facebook profile data
          if(!empty($userData)){
              $output  = '<h2>Facebook Profile Details</h2>';
              $output .= '<div class="ac-data">';
              $output .= '<img src="'.$userData['picture'].'"/>';
              $output .= '<p><b>Facebook ID:</b> '.$userData['oauth_uid'].'</p>';
              $output .= '<p><b>Name:</b> '.$userData['first_name'].' '.$userData['last_name'].'</p>';
              $output .= '<p><b>Email:</b> '.$userData['email'].'</p>';
              $output .= '<p><b>Gender:</b> '.$userData['gender'].'</p>';
              $output .= '<p><b>Logged in with:</b> Facebook</p>';
              $output .= '<p><b>Profile Link:</b> <a href="'.$userData['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 = '<h3 style="color:red">Some problem occurred, please try again.</h3>';
          }
      }else{
          // Get login url
          $permissions = ['email']; // Optional permissions
          $loginURL = $helper->getLoginUrl(FB_REDIRECT_URL, $permissions);
          
          // Render Facebook login button
          $output = '<a href="'.htmlspecialchars($loginURL).'"><img src="images/fb-login-btn.png"></a>';
      }
      ?>
      
      <!DOCTYPE html>
      <html lang="en-US">
      <head>
      <title>Login with Facebook using PHP by CodexWorld</title>
      <meta charset="utf-8">
      </head>
      <body>
      <div class="container">
          <div class="fb-box">
              <!-- Display login button / Facebook profile information -->
              <?php echo $output; ?>
          </div>
      </div>
      </body>
      </html>

       

Logout (logout.php)

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

  • Delete 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']);
    
    // Remove user data from session
    unset($_SESSION['userData']);
    
    // Redirect to the homepage
    header("Location:index.php");
    ?>

     

Conclusion

Firstly, we have tried to make the Facebook login implementation fast and straightforward. The example code integrates Facebook login with the Facebook SDK for PHP. Secondly, there is no need to add SDK library files separately. Our source code includes all the required data with SDK v5 for PHP. In conclusion, you only need to specify some minimum settings to add a login system with Facebook to your website using PHP. To make Facebook more user-friendly, you can use the JavaScript SDK to integrate Facebook login without refreshing the page using JavaScript.

RELATED POSTS

What is Application Programming Interface (APIs)?

Like Dislike Rating System with jQuery, Ajax, and PHP

Star Rating System with jQuery, Ajax, PHP, and MySQL

Also, read our previous blog-Login with Facebook using JavaScript SDK

Tags: FacebookPHP
ShareTweetSendShareSharePinScan
Lakshika Mathur

Lakshika Mathur

Related Posts

What is Application Programming Interface (APIs), Types, and Importance.
PHP and MySQL

What is Application Programming Interface (APIs)?

January 29, 2022
127
Like Dislike Rating System with jQuery, Ajax, and PHP
jQuery & AJAX

Like Dislike Rating System with jQuery, Ajax, and PHP

January 6, 2020
831
Star Rating System with jQuery, Ajax, PHP, and MySQL
jQuery & AJAX

Star Rating System with jQuery, Ajax, PHP, and MySQL

January 6, 2020
183
How to Force Download File in PHP
PHP and MySQL

How to Force Download File in PHP

January 2, 2020
87
How to Connect to the Remote MySQL Database using PHP
PHP and MySQL

How to Connect to the Remote MySQL Database using PHP

January 1, 2020
29
How to Generate QR Code with PHP using Google Chart API
PHP and MySQL

How to Generate QR Code with PHP using Google Chart API

January 1, 2020
116
Next Post
Login with Twitter using PHP

Login with Twitter using PHP

Login with GitHub OAuth API using PHP

Login with GitHub OAuth API using PHP

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Categories

  • Comparison (3)
  • HTML & CSS (9)
  • Interesting Facts (1)
  • JavaScript (27)
    • jQuery & AJAX (18)
  • PHP and MySQL (48)
  • Security (10)
  • SEO (2)
  • Trademark (2)
  • Tutorials (5)
  • Uncategorized (1)
  • Web Hosting (19)
    • VPS Server (5)
  • WordPress (8)

Recent Posts

  • Is the Trademark valuable to your Brand or domain?
  • Ideas For Ten Fantastic Online Business From Home
  • Some best free WordPress Themes for Affiliate Marketing Websites
  • Home
  • Posts
  • Privacy Policy
  • Terms and Conditions

Built and Maintained With ♥ by AllsWeb Team

No Result
View All Result
  • Home
  • Main Home
  • PHP and MySQL
  • JavaScript
    • jQuery & AJAX
  • WordPress
  • SEO
  • Web Hosting
  • Comparison

Built and Maintained With ♥ by AllsWeb Team

Go to mobile version