Nowadays the web users are not interested in filling out a big form for registration on the website. The short registration process helps to get more subscribers to your website. Login with Facebook is a quick and powerful way to integrate registration and login system on the website. Facebook is the most popular social network, and most of the users have a Facebook account. Facebook Login allows users to sign in to your website using their Facebook account credentials without signing up on your website.
PHP SDK allows accessing the Facebook API from the web application. You can easily implement the Login with Facebook account using Facebook SDK for PHP. This tutorial will show how you can implement user login and registration system with Facebook using PHP and store the user profile data into the MySQL database. Our example Facebook Login script uses Facebook PHP SDK v5 with Facebook Graph API to build Facebook Login system with PHP and MySQL.
To get started with the latest version of Facebook SDK v5.x, make sure your system meets the following requirements.
Before you begin to integrate Login with Facebook using PHP, take a look at the file structure.
facebook_login_with_php/ ├── config.php ├── dbConnect.php ├── index.php ├── logout.php ├── facebook-graph-sdk/ ├── images/ │ ├── fb-login-btn.png └── css/ └── style.css
To access Facebook API you need to create a Facebook App and specify the App ID & App Secret at the time of calling the Facebook API. Follow the step-by-step guide to create Facebook App and generate App ID & Secret in the Meta apps dashboard.
Note that: The App ID and App secret need to be specified in the script at the time of Facebook API call. Also, the Valid OAuth Redirect URIs must be matched with the Redirect URL that specified in the script.
To store the user’s profile information from Facebook, a table needs to be created in the database. The following SQL creates a users table with some basic fields in the MySQL database to hold the Facebook account information.
CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`oauth_provider` varchar(50) DEFAULT NULL COMMENT 'FACEBOOK/GOOGLE/X/LINKEDIN',
`oauth_uid` varchar(100) DEFAULT NULL,
`first_name` varchar(25) DEFAULT NULL,
`last_name` varchar(25) DEFAULT NULL,
`email` varchar(50) DEFAULT NULL,
`picture` varchar(255) DEFAULT NULL,
`created` datetime NOT NULL DEFAULT current_timestamp(),
`modified` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
The PHP SDK library allows you to access the Facebook Platform service from a PHP web application. In this example script, the facebook-graph-sdk directory contains the latest version (v5) of the Facebook SDK for PHP.
Note that: You don’t need to download it separately, all the required files of Facebook PHP SDK v5 are included in our Facebook Login PHP source code.
In the config.php file, constant variables of the Facebook API and database settings are defined.
Facebook API Constants:
Database Constants:
Call Facebook API:
<?php
// Facebook API configuration
define('FB_APP_ID', '_Facebook_App_ID_HERE_');
define('FB_APP_SECRET', '_Facebook_App_Secret_HERE_');
define('FB_REDIRECT_URL', '_Callback_URL_HERE_');
// Database configuration
define('DB_HOST', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', 'root');
define('DB_NAME', 'codexworld_db');
// Start session
if(!session_id()){
session_start();
}
// Include the autoloader provided in the SDK
require_once __DIR__ . '/facebook-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;
}
?>
Note that: You’ll find the App ID and App Secret on your Facebook App settings page.
The dbConnect.php file is used to connect the database using PHP and MySQL.
<?php
// Connect with the database
$db = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);
// Display error if failed to connect
if ($db->connect_errno) {
printf("Connect failed: %s\n", $db->connect_error);
exit();
}
?>
In the index.php file, the Facebook API authentication process is handled using PHP.
getLoginUrl() method of the login helper class, and the Facebook Sign-in button is displayed on the web page.<?php
// Include configuration file
require_once 'dbConnect.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: ./");
exit;
}
// Getting user's profile info from Facebook
try {
$graphResponse = $fb->get('/me?fields=name,first_name,last_name,email,picture');
$fb_user = $graphResponse->getGraphUser();
} catch(FacebookResponseException $e) {
$fb_api_error = 'Graph returned an error: ' . $e->getMessage();
} catch(FacebookSDKException $e) {
$fb_api_error = 'Facebook SDK returned an error: ' . $e->getMessage();
}
if(!empty($_SESSION['fb_api_error'])){
// Remove existing data from session
session_destroy();
// Store error message in session
$_SESSION['fb_api_error'] = $fb_api_error;
// Rediect to the login page
header("Location: ./");
exit;
}
if(!empty($fb_user)){
// Hold user profile data in array
$userData = array(
'oauth_uid' => !empty($fb_user['id'])?$fb_user['id']:'',
'first_name' => !empty($fb_user['first_name'])?$fb_user['first_name']:'',
'last_name' => !empty($fb_user['last_name'])?$fb_user['last_name']:'',
'email' => !empty($fb_user['email'])?$fb_user['email']:'',
'picture' => !empty($fb_user['picture']['url'])?$fb_user['picture']['url']:''
);
// Check whether the user already exists in the database
$stmt = $db->prepare("SELECT id FROM users WHERE oauth_uid = ?");
$stmt->bind_param("s", $userData['oauth_uid']);
$stmt->execute();
$stmt->store_result();
//$stmt->close();
if($stmt->num_rows > 0){
$stmt->bind_result($user_id);
$stmt->fetch();
// Update user data in the database
$sqlQ = "UPDATE users SET first_name=?, last_name=?, email=?, picture=?, modified=NOW() WHERE id=?";
$stmt = $db->prepare($sqlQ);
$stmt->bind_param("ssssi", $userData['first_name'], $userData['last_name'], $userData['email'], $userData['picture'], $user_id);
$update = $stmt->execute();
}else{
$oauth_provider = 'FACEBOOK';
// Insert user data in the database
$sqlQ = "INSERT INTO users (oauth_provider,oauth_uid,first_name,last_name,email,picture,created,modified) VALUES (?,?,?,?,?,?,NOW(),NOW())";
$stmt = $db->prepare($sqlQ);
$stmt->bind_param("ssssss", $oauth_provider, $userData['oauth_uid'], $userData['first_name'], $userData['last_name'], $userData['email'], $userData['picture']);
$insert = $stmt->execute();
}
}
// Get logout url
$file_info = pathinfo(FB_REDIRECT_URL);
$BASE_RURL = isset($file_info['extension']) ? str_replace($file_info['filename'] . "." . $file_info['extension'], "", FB_REDIRECT_URL) : FB_REDIRECT_URL;
//$logoutURL = $helper->getLogoutUrl($accessToken, $BASE_RURL.'logout.php');
$logoutURL = $BASE_RURL.'logout.php';
}else{
// Get login url
$permissions = ['email']; // Optional permissions
$loginURL = $helper->getLoginUrl(FB_REDIRECT_URL, $permissions);
}
// Get error from session
$fb_api_error = '';
if(!empty($_SESSION['fb_api_error'])){
$fb_api_error = $_SESSION['fb_api_error'];
unset($_SESSION['fb_api_error']);
}
?>
<?php if(!empty($loginURL)){ ?>
<div class="profile-info">
<!-- Render Facebook login button -->
<a href="<?php echo htmlspecialchars($loginURL); ?>">
<img src="images/fb-login-btn.png" width="320">
</a>
</div>
<?php }elseif(!empty($userData)){ ?>
<!-- Display Facebook profile information -->
<div class="profile-container">
<img src="<?php echo !empty($userData['picture'])?$userData['picture']:'images/user.png'; ?>">
</div>
<div class="profile-info">
<h1><?php echo $userData['first_name'].' '.$userData['last_name']; ?></h1>
<p class="job-title"><?php echo $userData['email']; ?></p>
<p class="desc">Profile ID: <span><?php echo $userData['oauth_uid']; ?></span></p>
</div>
<div class="profile-social">
<a href="<?php echo $logoutURL; ?>" class="btn btn-primary">Logout</a>
</div>
<div class="card-bottom"></div>
<?php }else{ ?>
<div class="alert alert-danger">
<?php echo !empty($fb_api_error)?$fb_api_error:'Oops! Something went wrong. Please try again later.'; ?> <a href="index.php">Start Over</a>
</div>
<?php } ?>
If the user wishes to log out from their Facebook account, the logout.php file is loaded.
<?php
// Include configuration file
require_once 'config.php';
// Remove access token from session
unset($_SESSION['facebook_access_token']);
// Redirect to the homepage
header("Location: index.php");
exit;
?>
Login with Facebook using JavaScript
In this tutorial, we’ve tried to make Facebook Login implementation quicker and easier. The example code integrates Facebook Login with the Facebook SDK for PHP. You don’t need to add the SDK library 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. To make the Facebook login more user-friendly, you can use JavaScript SDK to integrate Facebook Login without page refresh using JavaScript.
Looking for expert assistance to implement or extend this script’s functionality? Submit a Service Request
💰 Budget-friendly • 🌍 Global clients • 🚀 Production-ready solutions
Your code helped me a lot. Thanks for that . I want know how can we implement as API call. Can you please help me..
I searched a lot , but i didnt unable to get it
Is the config.php suppose to be included in every file in the site or just the authentication files, login, logout files?
Hello,
where can i find the image and css files?
Download the source code.
Thanks for this tutorial,
I want to insert the contact number in the database, how to do that?
Thanks again codexworld…
Must facebook approve the permission befor i can integrate login? If yes, how long does it take
No, App Review doesn’t require for the Default Public Profile Fields. This permission is approved by default in Facebook App, so it doesn’t need to be approved before Facebook Login integration.
Thanks #codexworld !, I want to ask if you have another way to allow me to pay for your wonderful source code? I want to pay for it, but I’m a student, I don’t have credit card, much less the Paypal account….
P.S. Sorry for my bad english, I’m still learning it..
It works on only localhost, but gives me error when i tried using it online error (URL Blocked: This redirect failed because the redirect URI is not whitelisted in the app’s Client OAuth Settings. Make sure Client and Web OAuth Login are on and add all your app domains as Valid OAuth Redirect URIs.)
This issue occurred because of the Facebook App settings. Please check whether you have specified the Redirect URL in Facebook App settings.
Excellent!!! thank you very much for this great contribution … just a detail … I do not want to save in the database … of rest everything perfect … I do not know if you can help me … in advance thanks
Hi,
I have integrated Facebook and google account in website by following your tutorial. Thanks .
I am having some doubts to clarify, What would I need to do to display my some other page instead of the profile information page? I tried several ways but nothing works.
Thanks man, waiting for your reply.
Hello, i just purchased your code. it working perfect. saved my time. Thank you so much. Only problem i am facing is the profile image of facebook is very small in size. like 50 * 50 px. How can i fix this. atleast little bit better resolution..
Follow this guide to get large size profile picture in Facebook PHP SDK – https://www.codexworld.com/how-to/get-large-size-profile-picture-in-facebook-php-sdk/
Is it working with the new FB api that use https?
Yes, it will work.
Would this need to be modified slightly in order to handle multiple Facebook apps on the same server?
1. Copy db table users to users2, users3, etc. ?
2. change $_SESSION[‘facebook_access_token’] -> $_SESSION[‘facebook_access_token2’], $_SESSION[‘facebook_access_token3’]
Thanks!
actly everything went fine , except for one thing, In facebook login the image quality is much less, and I tried to resize using html paramters , but didn’t worked as I expected. Is there any way to get high quality profile pictures
Yes, you can get large size profile picture from Facebook, see this tutorial – https://www.codexworld.com/how-to/get-large-size-profile-picture-in-facebook-php-sdk/
Hello, any ideas if i want to implement two social login (Facebook & Twitter) ? How to combine two php code in one file .php? Is it using function? Thankyou.
Great Coding codeworld….. i want to pop up facebook login.how to do? please help
See this tutorial to integrate Facebook login with popup – https://www.codexworld.com/login-with-facebook-using-javascript-sdk/
Thanks codexworld. Petmalu. easy to used! Nice Coding.
Helllo
How to rename the main folder ‘login with facebook using php’ to another name ? kindly advice
Regards
hello,
i am getting error like this….
Can’t Load URL: The domain of this URL isn’t included in the app’s domains. To be able to load this URL, add all domains and subdomains of your app to the App Domains field in your app settings.
Please help me to fix the error
You need to specify the website’s domain in App Domains field. See this step-by-step guide to create and configure the Facebook App – https://www.codexworld.com/create-facebook-app-id-app-secret/
I don’t understand this well, I read the official developer site, search Google and found this. Do I need to download Facebook SDK first
No, you don’t need to download it separately. Download our source code, it contains all the required files and Facebook SDK.
great work thanx. How can i get a bigger version of facebook profile picture. It shows only 50*50 px version and when i try to get the bigger picture manually using it shows error: Invalid URL signature
See this guide to get large size profile picture in Facebook PHP SDK – https://www.codexworld.com/how-to/get-large-size-profile-picture-in-facebook-php-sdk/
Hi,
I have FB and Google login working together on the same page, but the FB logout breaks when Fb and Google logins are both on the same page.
Any ideas?
just awesome……….
Awesome…..integrated fb and google both. Thanks.
Hi, Thanks for writing this tutorial this is very helpful.
I want to know how can i run it over PHP 5.2 ?
hi, how to handle facebook login when user denied access to email permission? do I have to re-request the permission? or make form for user to insert permission?
how to download facebook sdk library
Our source code contains all the required files including Facebook PHP SDK, download the source code ZIP.
HI There
Great script!! Searched for a while for a good implementation.
What would the script be for checking if the session is set? I need to add this to the page of every page to ensure the user is logged in.
I have a website for users with multiple pages and every page must check if the user is logged in else, redirect to index.
Thanks
Thank you #codexworld for this tutorial and complete script, its work in my website. I need one more thing to done, can you please tell me how can i show a message when a user logged in and logged out using this script?