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 will use Facebook PHP SDK with Facebook Graph API to build Facebook Login system with PHP and MySQL.

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

  • inc/
    • base_facebook.php
    • facebook.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 (codexworld). At first, create a database (like codexworld) and run the below SQL on the database. The following SQL creates a users table to the database for inserting user 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(5) 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;

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

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


//Include Facebook SDK
require_once 'inc/facebook.php';

 * Configuration and setup FB API
$appId 'InsertAppID'//Facebook App ID
$appSecret 'InsertAppSecret'// Facebook App Secret
$redirectURL 'http://localhost/facebook_login_with_php/'// Callback URL
$fbPermissions 'email';  //Required facebook permissions

//Call Facebook API
$facebook = new Facebook(array(
'appId'  => $appId,
'secret' => $appSecret
$fbUser $facebook->getUser();

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 Facebook account, the profile details would be displayed, otherwise, Facebook login button would appear.

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

$fbUser NULL;
$loginURL $facebook->getLoginUrl(array('redirect_uri'=>$redirectURL,'scope'=>$fbPermissions));
$output '<a href="'.$loginURL.'"><img src="images/fblogin-btn.png"></a>';     
//Get user profile data from facebook
$fbUserProfile $facebook->api('/me?fields=id,first_name,last_name,email,link,gender,locale,picture');
//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']['data']['url'],
'link'             => $fbUserProfile['link']
$userData $user->checkUser($fbUserData);
//Put user data into session
$_SESSION['userData'] = $userData;
//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="logout.php">Facebook</a>'
$output '<h3 style="color:red">Some problem occurred, please try again.</h3>';
?> <div><?php echo $output?></div>

Logout (logout.php)

When the user wishes to logout from their account, logout.php file is called.

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

//Unset user data from session

//Destroy session data

//Redirect to homepage

If you want to remove app permission on logout, place the following code after including the fbConfig.php file. App Permission screen will appear every time when the user tries to login in with Facebook.

//Remove App permissions
$fbUid $_SESSION['userData']['oauth_uid'];


In this tutorial, we’ve tried to make Facebook Login implementation quicker and easier. Using our script, you only need to include 2 API files (base_facebook.php and facebook.php) to integrate Login with Facebook in your website. If you have any query or suggestions about this tutorial and scripts, feel free to comment here.

Recommended Tutorials For You


  1. Amit Said...
  2. Subba Said...
  3. Kumar Said...
  4. Sandy Said...
  5. Subho Said...
    • CodexWorld Said...
  6. Daniel Ricc Said...
  7. Nicolas Said...
    • CodexWorld Said...
  8. Sastro Jahat Said...
  9. Priyanka Said...
  10. Stanley Said...
    • CodexWorld Said...
  11. Rahul Said...
  12. Satish Said...
  13. Satish Said...
  14. Rezz Said...
  15. Rommel Evangelista Said...
  16. Addrk Said...
  17. Jason Said...
  18. Manish Saraswat Said...
  19. Sai Said...
  20. Hemraj Said...
  21. Vilas Galave Said...

Leave a reply