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
$fbUserProfile[’email’] = !empty($fbUserProfile[’email’])?$fbUserProfile[’email’]:”;
where i set this code ??? for avoid the error
Place this code before defining the
$fbUserData. After modification, the code will look like the following.Sir, thanks for tutorial,
and my question is How to get fb username and save in database
I see https://www.codexworld.com/facebook-login-codeigniter/ very good tutorial, but can you with small changes public facebook login with Kohana?
Kohana is old version of CI.
Thx.
hello sir i need to fetch the user mobile number also could you please explain what changes i have to made in your script
thanks in advance
where can i DL Facebook PHP SDK v5.0
Our source code contains all the required files including Facebook PHP SDK, download the source code ZIP.
Everything was great, the script works, but I have one problem. Script not display email address. How do I get email address? User Profile displays all data, Just not display email! Where is the problem?
$fbUserData = array(
‘oauth_provider’=> ‘facebook’,
‘oauth_uid’ => $fbUserProfile[‘id’],
‘first_name’ => $fbUserProfile[‘first_name’],
‘last_name’ => $fbUserProfile[‘last_name’],
’email’ => $fbUserProfile[’email’], // error in this line sir plzzz solve it .Notice: Undefined index: email in C:\xampp\htdocs\facebook_login_with_php\index.php on line 6
‘gender’ => $fbUserProfile[‘gender’],
‘locale’ => $fbUserProfile[‘locale’],
‘picture’ => $fbUserProfile[‘picture’][‘url’],
‘link’ => $fbUserProfile[‘link’]
);
If the email has not associated with user’s Facebook profile,
$fbUserProfilearray will not containemail. You can use the following code to avoid this error.Hey nice post. I hope it’s alright that I shared it on my FB,
if not, no problem just tell me and I’ll delete
it. Either way keep up the good work.
How to change size and width of image profile ?
See this guide to get large size profile picture from Facebook – http://www.codexworld.com/how-to/get-large-size-profile-picture-in-facebook-php-sdk/
Please tell me how to implement all the api simultaneously
PLease i want to retrieve user phone, birth date and address ??????
Hello Sir , I copy and paste your code and it is working great . Kindly explain the flow of this project. I will be very thankful to.
I got some error like this plz help me
App Not Set Up: This app is still in development mode, and you don’t have access to it. Switch to a registered test user or ask an app admin for permissions.
You need to make the Facebook App public. Go to your Facebook App page ==> navigate to the “App Review” page and make your app live. For more details, see our app creation and setup tutorial – https://www.codexworld.com/create-facebook-app-id-app-secret/
My Current site PHP Version is 5.3.28
I get error like
PHP Fatal error: Uncaught exception ‘Exception’ with message ‘The Facebook SDK requires PHP version 5.4 or higher.’ in D:\INETPUB\VHOSTS\ainetix.com\qnabot.ainetix.com\facebook-php-sdk\autoload.php:32
Stack trace:
#0 fbConfig.php(27): require_once()
#1 index.php(6): require_once(‘D:\INETPUB\VHOS…’)
#2 \facebook-php-sdk\autoload.php on line 32
We’ve updated our script with Facebook PHP SDK v5 and it requires PHP version 5.4 or greater.
Thank you so much !!
Rangnath:
There was an update to the Facebook SDK a few days ago that broke the script. They’ve updated the script to work with it now, so you just have to update your implementation to fit with the updated tutorial! 🙂
We’ve used the latest version of SDK. You can check and let us know if any issue occurs.
I have installed this script and it was working before, but i tried today and it is not working fine. I click on the facebook login button it is redirecting fine and getting back to my website as well but again it is redirecting to facebook.
I found that after redirecting to my website $fbuser variable value is still 0.
Please help me on it.
hey…
Thanks for this tutorial…this helped me to guide through the user login in fb…..
actually i tested this out today….its pathetic that FB tutorial on their official website is not pretty self explanatory …I struggled a lot….
Regards
Amit Anand
Hi my is subba i am using this code in my project in response i want to access token value also how to get that value please give me any solution
pls tell me how to integrate this with wordpress..
it’s urgent sir
I am worked on all social login. They are working properly. But i want all social icon is on one page. So please can you help for that. I have done linked in and twitter but facebook url redirect to twitter. PLease help me…!!
Here, it’s clear that to get user email we should use $userData[’email’] that is email field. My question is if one user is registered with phone number(without email) then what field should I use to get the use’s information
@Subho If the user use mobile to register, Facebook creates an email for that user and sets it primary email. So, you’ll get the user email although the user has not registered with email.
hello thanks a lot for this tutorial and files…only one thing…when a do “logout”…it doesn´t make logout from facebook, how can i do to make user logout from facebook too?? thanks!!!
Everything was great, the script works, but I have one problem. Script not display email address. How do I get email address? User Profile displays all data, Just not display email! Where is the problem?
@Nicolas You should need to specify scope (
'scope' => 'email') to get user email address. Please see the above source code.thank you
hi sir.
i want to fetch friends name list of user…
how i can add in database and fetch through array
Nice tutorial…Thanks Man.
But it doesn’t save the information in my local database…Please how do i go about it?
@Stanley Make sure you have changed the $dbServer, $dbUsername, $dbPassword and $dbName variable’s value as per your database credentials in
includes/functions.phpfile.how can i get mobile no
how to get friends list from facebook in php
thanks sir
thanks bro
Sir can you help us how to integrate this codes to CodeIgniter?
@Rommel We’ve already published Login with Facebook in CodeIgniter tutorial, see it from here – http://www.codexworld.com/facebook-login-codeigniter/
@Manish Saraswat
Hi, u can use the “Permissions Reference” page here: (https://developers.facebook.com/docs/facebook-login/permissions/)
Ex, for extra – about – information:
And for cellphone, u need send to Facebook one request.
See this… (https://developers.facebook.com/blog/post/2011/01/14/platform-updates–new-user-object-fields–edge-remove-event-and-more/)
You are awesome! thank you for this
yeah, this really very good tutorial, but i need some extra information from facebook api. like “mobile number”, “bio”, “about”. I tried but i am unable to get this information. so plz someone help me
Is it working for websites with “https” ?
how to fetch facebook friend list
How can I get friend list of logged in user?
Ok Thanks
Sir,
What is facebook permissinon Email id???
@Mantu To get the user email you need to specify the permission as
email.Great tutorial!
I am looking to send myself an email every time an existing user logs in. How would I go about doing that? Any tips/suggestions?
Alternatively, saving a record to the DB each time a user logs in would be helpful as well. Any thoughts on where in your code this be implemented?
Thank you!