Login with Facebook using PHP

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, localhost domain 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.
  • 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 codexworld) 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` (
 `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,
) 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.

class User {
$dbHost     "localhost";
$dbUsername "root";
$dbPassword "";
$dbName     "codexworld";
$userTbl    'users';
// Connect to the database
$conn = new mysqli($this->dbHost$this->dbUsername$this->dbPassword$this->dbName);
"Failed to connect with MySQL: " $conn->connect_error);
$this->db $conn;
checkUser($userData = array()){
// 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);
$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);
// 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.


// Include the autoloader provided in the SDK
require_once __DIR__ '/facebook-php-sdk/autoload.php';

// Include required libraries
use Facebook\Facebook;

 * 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 token
try {
$accessToken $_SESSION['facebook_access_token'];
$accessToken $helper->getAccessToken();
} catch(
FacebookResponseException $e) {
'Graph returned an error: ' $e->getMessage();
} catch(
FacebookSDKException $e) {
'Facebook SDK returned an error: ' $e->getMessage();


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.

// Include FB config file && User class
require_once 'fbConfig.php';

// 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
// Redirect the user back to the same page if url has "code" parameter in query string
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) {
'Graph returned an error: ' $e->getMessage();
// Redirect user back to app login page
header("Location: ./");
    } catch(
FacebookSDKException $e) {
'Facebook SDK returned an error: ' $e->getMessage();
// 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
$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>'
$output '<h3 style="color:red">Some problem occurred, please try again.</h3>';
// 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 CodexWorld</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.

// Include FB config file
require_once 'fbConfig.php';

// Remove access token from session

// Remove user data from session

// Redirect to the homepage


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.

Are you want to get implementation help, or modify or extend the functionality of this script? Submit paid service request

Recommended Tutorials For You


  1. Mike Said...
  2. Shagal A Sajid Said...
  3. Nathan Said...
  4. Vikas Said...
  5. Mark Said...
  6. Tamer Said...
  7. Rukku Said...
  8. Abiola Oyeniyi Said...
    • CodexWorld Said...
  9. Mohamed Said...
  10. Satchmo Said...
  11. Shawkat Said...
  12. Mohit Said...
  13. Max Said...
  14. Yeh Said...
  15. Neeraj Patidar Said...
    • CodexWorld Said...
  16. Shaun Said...
  17. Jony Sheikh Said...

Leave a reply