Login with Facebook using PHP

Create a Facebook App

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.

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

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, 

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.

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

Database Constants:

Facebook API Constants:

Call Facebook API:

<?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.

Logout (logout.php)

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

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.

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

Exit mobile version