In this article, you will get a simple way to integrate Facebook login in PHP. I have provided here a simple source code to set up a Facebook login system that will be more helpful for you.
I will teach you how to log in using a Facebook account on the website and fetch the user’s data from their Facebook profile to save it into the MySQL database.
Before getting started with this tutorial, I suggest you read all the given steps without skipping any one of them. Because every step has a useful PHP script & a concept that will help you easily to integrate Facebook login system to your website.
Login with Facebook Using PHP
Most of the users don’t want to create their own multiple accounts, they always want to login to the websites with their Facebook account. So Facebook has provided the login system to solve user’s signup problem,
Facebook login system allows the users to use their Facebook profile credentials to the other websites. If you integrate the Facebook login system into your website, users will not have to create a new account. simply they can log in with their credentials of Facebook account.
Now, I am going to explain the integration of Facebook login in PHP through the following steps.
1. Create Folder Structure
Create your Project folder the same as the following structure.
myproject |__css |__facebook-login/ | |__php-graph-sdk-5.x | |__facebook-api-setting.php | |__facebook-login-setup.php | |__facebook-profile-data.php |__dashboard.php |__login.php |__logout.php
2. Get Graph API for PHP
You will have to get the Facebook login API for PHP to integrate Facebook login. So Facebook has provided API as the Facebook Graph API to use Facebook Login purpose.
Process to get
- Click on Facebook Graph API to get it.
- you will be redirected to GitHub then get the ZIP folder and extract it.
- Rename API folder like php-graph-sdk-5.x
- Keep it in the facebook-login folder.
3. Get Facebook App ID & App Secret
To integrate Facebook login, you must have the Facebook App ID & App Secret. So, to get the Facebook App ID & App Secret, you will have to create a Facebook app through the following steps.
Also, Open URL How to create a Facebook App id and Secret key to learn to create a new app account.
- Create APP Account
- Open the official URL developers.facebook.com to create the Facebook App
- Log in with your Facebook account.
- Click on Get Started option at the top right side of the Facebook navbar
- Click on the Next button.
- then click on the Developer rectangle box.
- Click on Create First App
- Enter Display Name & Contact Email
- Click on Create App Id
- App Dashboard will open
- Register Website domain to App
- The following steps are given to register the website category & domain
- Click on setting
- Click on Basic
- Enter website domain & select its category
- Click on Save Changes
- Facebook Login to Set Up
- Click on product+
- Select Facebook login
- Select Web option
- Enter Website URL & save
- Settings of Facebook Login
- Enter Redirect URL into the Valid OAuth Redirect URIs field.
- Click on Save Changes
- Get App Id & App Secret
- got to setting>basic and get there App Id & App Secret
4. Create MySQL Database & Table
You need to create a database & table to store Facebook profile information of users in the phpMyAdmin as the following capture.
- Database Name – codingstatus
- Table Name – fblogin
5. Configure Facebook API
To configure Facebook API, you have to go through the following steps –
- Create class FB_API
- Write database connection script
- Assign Facebook App Id, App Secret Key, API path & dashboard path Where the user will redirect after getting logged in.
File Name – facebook-api-setting.php
<?php // Database Connection class FB_API{ public $hostname= 'localhost'; // Enter Your Hostname public $DBusername= 'root'; // Enter your database username public $DBpassword= ''; // Enter your database password public $DBname= 'codingstatus.com'; // Enter your database name public $usersTableName= 'fblogin'; // Enter your users table name // Facebook API Key public $FB_APP_ID= '2232558247037604'; // Enter your fb App ID public $FB_APP_SECRET='4b5a1e1585968176e0a6aabb5c66b224'; // Enter your fb Secret key public $FB_REDIRECT_URL= '../dashboard.php'; // Enter page address where it will redirect after login // Facebook API Path public $FB_API_path='/php-graph-sdk-5.x/src/Facebook/autoload.php'; /* keep as it is your api folder same like this*/ } ?>
6. Store Facebook profile data.
To store Facebook profile data, you have to implement the following things –
- Create a class FB_Users and extend properties & methods from FB_API
- Define database connection within a constructor method
- Create a function
validUser()
with an array type parameter$userData
to fetch profile data of the Facebook user from the database
File Name – facebook-profile-data.php
<?php class FB_Users extends FB_API { function __construct(){ if(!isset($this->db)){ // Connect to the database $conn = new mysqli($this->hostname, $this->DBusername, $this->DBpassword, $this->DBname); if($conn->connect_error){ die("Database is not connected: " . $conn->connect_error); }else{ $this->db = $conn; } } } function validUser($userData = array()){ if(!empty($userData)){ // Check whether user data already exists in database $getQuery = "SELECT * FROM ".$this->usersTableName." WHERE oauth_provider = '".$userData['oauth_provider']."' AND oauth_uid = '".$userData['oauth_uid']."'"; $getResult = $this->db->query($getQuery); if($getResult->num_rows > 0){ // Update user data if already exists $SQLquery = "UPDATE ".$this->usersTableName." 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($SQLquery); }else{ // Insert user data $SQLquery = "INSERT INTO ".$this->usersTableName." 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($SQLquery); } // Get user data from the database $result = $this->db->query($getQuery); $userData = $result->fetch_assoc(); } // Return user data return $userData; } } ?>
7. Setup Facebook login
To setup Facebook login, you will have to write code according to the following steps –
- First of all, include
facebook-api-setting.php
and after that includefacebook-profile-data.php
- Define all the code of the Facebook library. Don’t worry, you will get it in the following file
File Name- facebook-login-setup.php
<?php require_once 'facebook-login/facebook-api-setting.php'; require_once 'facebook-login/facebook-profile-data.php'; // Initialize database connection $user = new FB_Users(); if(!session_id()){ session_start(); } require_once __DIR__ .$user->FB_API_path; // Facebook API Liberary use Facebook\Facebook; use Facebook\Exceptions\FacebookResponseException; use Facebook\Exceptions\FacebookSDKException; // Facebook API $fb = new Facebook(array( 'app_id' => $user->FB_APP_ID, 'app_secret' => $user->FB_APP_SECRET, 'default_graph_version' => 'v3.2', )); //redirect login helper $helper = $fb->getRedirectLoginHelper(); // accessing 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; } if(isset($accessToken)){ if(isset($_SESSION['facebook_access_token'])){ $fb->setDefaultAccessToken($_SESSION['facebook_access_token']); }else{ // short-lived access token in session $_SESSION['facebook_access_token'] = (string) $accessToken; // OAuth 2.0 client handler $oAuth2Client = $fb->getOAuth2Client(); // short-lived access token for a long-lived one $longLivedAccessToken = $oAuth2Client->getLongLivedAccessToken($_SESSION['facebook_access_token']); $_SESSION['facebook_access_token'] = (string) $longLivedAccessToken; //default access token $fb->setDefaultAccessToken($_SESSION['facebook_access_token']); } // Redirect the user back if(isset($_GET['code'])){ header('Location: ./'); } // 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(); // user back to app login page header("Location: ./"); exit; } catch(FacebookSDKException $e) { echo 'Facebook SDK returned an error: ' . $e->getMessage(); exit; } // 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']:''; // Insert or update user data to the database $fbUserData['oauth_provider'] = 'facebook'; $userData = $user->validUser($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)){ echo '<script>alert("Error, please try again");</script>'; }else{ } }else{ // Get login url $permissions = ['email']; // Optional permissions $loginURL = $helper->getLoginUrl($user->FB_REDIRECT_URL, $permissions); // Render Facebook login button $fbLoginButton = '<a href="'.htmlspecialchars($loginURL).'" class="fb-login">Login with Facebook</a>'; } ?>
8. Create Facebook Login Page
Write a basic HTML code and print $fbLoginButton
to display the Facebook login button on the page
File Name- login.php
<?php include('facebook-login/facebook-login-setup.php'); ?> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0"> <title>Simple Way to Integarate Facebook Login in PHP</title> <link rel="stylesheet" href="css/style.css"> </head> <body> <div class="container"> <div class="fb-box"> <?php echo $fbLoginButton; ?> </div> </div> </div>
You can use the following CSS code to design your login page otherwise write your own custom CSS code.
File Name- style.css
.login-box { width: 20%; padding: 10px; background: #dcdada; } .custom-login input{ display: block; margin: 10px; padding: 5px; font-size: 20px; width: 88%; border: 1px solid #b1a2a2; } .custom-login input[type='submit']{ width: 93%; background: #f97402; color: white; font-size: 20px; border: 0px; } .fb-login{ background: #4267b2; color: white; text-decoration: none; padding: 7px; width: 87%; display: block; text-align: center; margin: 10px; }
9. Create a Dashboard Page
You should create a dashboard page to redirect after logging in through the Facebook
File Name- dashboard.php
<?php if(!session_id()){ session_start(); } $userFbData=$_SESSION['userData'] $first_name=$userFbData['first_name']; $last_name=$userFbData['last_name']; $gender=$userFbData['gender'] $email=$userFbData['email'] ?> <?php include('facebook-login/facebook-login-setup.php'); ?> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0"> <title>Simple Way to Integarate Facebook Login in PHP</title> </head> <body> <div class="container"> <h1>Welcome to dashboard</h1> </div> </body> </html>
10. Create Logout
To create logout, you have to write the following line of code
- First of all, start the login session
- After that, destroy the created login session
- At last, redirect to login page
File Name – logout.php
<?php session_start(); session_destroy(); header("Location:login.php"); ?>
Important Notes –
To use my above code in your project by going through the following points.
Create a facebook-login folder the same as the above structure.
Keep all the above codes as it is given above with the same file name.
keep remembering that all the PHP Facebook login codes file must be inside the facebook-login folder.
just include the facebook-login-setup.php
file in the custom login page of your project as following
Print $fbLoginButton
to create the Facebook login button on your custom login page.
My Suggestion
Dear Developers, I hope that you can easily integrate the Facebook login system on your websites by reading the above explanation.
If you have any queries related to web coding, you can ask me through the below comment box. So, Continue to visit my website, I will share more articles related to web coding to make easy your coding process.
thanks it works well