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
This is the best facebook login using php ever. It’s very easy to set up.
How to change the session time? It lasts only 20 minutes.
@Barret
You can increase the PHP session time as per your needs using the following code.
hi.. thanks for excellent script. just 1 problem here. When i click logout link, the page navigated to the right page – index.php. But it seems like did not killed the session. Because when i clicked Login image once again, it brought me direct to “facebook profile details” screen.
am i missing something here?
FYI – i use this script at my localhost (laptop).
thanks bro.
I think you have removed an important file from your download… in a comment you mention ACCOUNT.PHP , which is not in the pack. I’m a beginner but to me it looks like there is something missing.
I also noticed that the variable “$return_url” is not in use in any of th files in the pack.
Could you fix that please? HEEEELP!!!
@Fahed
The latest version of our script does not require the account.php page and $return_url variable. We’ve already updated our code but miss the $return_url variable. Thanks for your comment, we’ve updated our code.
thank u sir .i implemented successfully in localhost but after hosting it in server .after log in facebook data of user is not displaying
@Akshay
You need to add the server domain into the Facebook App Domains and modify the Site URL with your server URL.
Thanks for the tutorials
Hi, I’m Ari, from Brazil! Great work! It works very well. How to change the expiration time, or to using cookies? It very quickly auto loggs off!
i want to use it on my website i see your code but after that how can i use it on my website?
Can you please help me to do this?
i am very beignner in php
@Kiran
You can easily integrate FB login in your website. Just Download the full script and read our tutorial. If you are still need help, then let us know.
I have got the above tutorial working. I want to get the user access token for further api calls. How can I get the user access token from above code and then extend it for 60 days ?
Thanks for tutorial only i need how to get profile image from Facebook?
@Goran
Profile picture fetching is included in our latest script. Download our latest script from the above download link.
Hi Bro, thanks for the great tutorial, works like a charm!
Hello, thanks for your comment Codexworld ! where is the subscribe button anyway,
hi i have some problem how can i make register, login and logout in codeignbter by using media social ?
will you hear my problem now ?
1. my web let say it SIMPLE CRUD but the user can login waht they want (Facebook, Twitter, Google + )
so they log in then input same products, how can i make every user can login what they want and also save their input products !”
will big thanks if you create tutorial like that cuase everyone lookingfor it
Hi,
I done the the tutorials what you have did is running, But instead of localhost i need to use the IP address for my server to redirect. How can i use the IP address of server instead of localhost.
@Vignesh
Go to the FB apps page and click on the Settings links from the left side menu bar. Under the Website section, change the Site URL with your server IP address.
hi how can i applicated this to codiegnter ?
@Freddy
We will publish Login with Facebook in CodeIgniter tutorial soon. Please subscribe your email with us for getting this tutorial in your mail box.
This is a great tutorial. Really simple to get running on your own domain in a matter of minutes. Thanks very much for the info. I’ve since modified to include other permissions on facebook, and integrated with a members own section on a client website. Brilliant stuff.
I have seen the code. It is working fine. But I am getting an issue, the table in the database is not being filed with the logged in user information.
Please help me.
Thanka
Thank you sir.. Its great and simple code for fb login, working perfectly for me.
So far works great except that it registers nothing in the database… are you sure it is really working example?? all the other login tutorials work great except this one =(
Hi Antonio,
This script is well tested and it is working fine. Please check your database configuration into
__construct()function at theincludes/functions.phpfile@Deepak @shanmugam @JQ @Ajit
We are extremely sorry for that. We have resolved this issue and updated the code. Please download the updated code from the Download link.
Thanks for notify us on this issue.
Hello Sir,
I have read your blog on facebook login using php. It’s an awesome blog and contains useful information. Thank you for your blog.
Sir actually when i implement that blog i have facing a problem that only facebook ID is showing to me and no other information is showing. I have followed all your each and every step carefully but didn’t get any solution of my problem. Also my facebook app is live and have permission of accessing information from facebook user.
Sir kindly help me to get out from this solution.
Thanks in Advance
Hi. shangmugam and I have the same problem. I have an app that has live permission to access email and public_profile
I have checked in my database also. But no values in Email, name column. I am new to Php.
I used above code. but except facebook id everything gives null value only.
Hi! I’m having problem with permissions. I’m able to do the login thing but the request only gives my facebook id. Names, email, etc. are blank. What seems to be the problem here? Thanks!
Hi JQ,
Are you follow our Facebook apps creation steps? If not, then please follow our Facebook apps creation steps at the beginning of our tutorial. If you need more help please let us know.
Sir i want to know value of gender , email ,lastname,first_name coming from which page , because in “base_facebook.php” only one value we are returning that is “return $user_info[‘id’];” but not returning all value.
According to me problem coming from here,,
thanx sir to give me your valuable time
Hello sir , as you told for some changes in account.php i have done but same problem (error) occurring and bottom of the page one exception is coming “Some problem occurred, please try again.”
This error will come when
$user_datais empty. Are you modify$user_datavariable value with$user_profileintoindex.php? (as per mentioned earlier) If yes, then logout from your account and login again.Hi sir
i am getting error in index.php on line no 12
Error is ” Notice: Undefined index: first_name in C:\wamp\www\facebook_login_with_php\index.php on line 12″,
i have change line no 12 code ,As you mentioned in previous comment ,i have removed line 12 from code and write $user_data = $user_profile instead of that line,,but after changing this code i got another error “This webpage has a redirect loop
ERR_TOO_MANY_REDIRECTS”.
please sir give me some solution i am waiting for your reply
thank you in advance
This is happening because you have used this system without database. You need to do some modifications including the previous one.
Open the
account.phpfile and make the following changes.1. At line no.3 change
$_SESSION['userdata']['oauth_uid']to$_SESSION['userdata']['id'].2. Under the Facebook Profile Details display section change all
$_SESSION['userdata']['fname']to$_SESSION['userdata']['first_name']and$_SESSION['userdata']['lname']to$_SESSION['userdata']['last_name'].Please check and let us know if you need any other help.
I need extra addition to this code. I want to feed 2 more details in to the database which will be user input taken at the time of form submission.
Hi , it’s a great tutorial but it seems you have made it with database, is it possible to create without database like the below video.
I have found a video, check this and please let me know if it can be work.
Thanks Abhi.
You can easily create it without any database with our script. Please follow the below steps.
1. Open the
index.phpfile and go to the line no.12.2. Remove the code from line no.12 to 13 and insert this code
$user_data = $user_profile.3. Now you can get the user profile details from
$_SESSION['userdata'].Please let us know if you need any further help.
if i wan´t to get users birthday? what should i do?
sorry for the bad english
how to send mail from localhost using wamp if yes please tell procedure
See this tutorial to send email from localhost in PHP – https://www.codexworld.com/how-to-send-email-from-localhost-in-php/
I am getting following error ! Plz help !
Uncaught exception ‘Exception’ with message ‘Facebook needs the CURL PHP extension.’ in C:\wamp\www\inc\base_facebook.php on line 19
You need to enable CURL in PHP. Please follow the below steps.
1. Uncomment the following line in your php.ini file by removing the semicolon (;).
;extension=php_curl.dll
2. Restart your Apache server.
You are offering an essential information. I’ll be your regular visitor.
My partner and I stumbled over here from a different website
and thought I might check things out. I like what I
see so now i am following you. Look forward to
looking over your web page again.
This is excellent blog.
An excellent read. I’ll definitely be back.
Hі just read through this poѕt and wanted to sаy it was very
wel written. You’ve got a new fan.
You diԁ a greаt job wіth tthis post, thanks very mսch.
I am genuinely thankful to the owner of this web site who has shared this
impressive post at at this time.
Hi, I check your blog daily. Your humoristic style is awesome, keep doing
what you’re doing!
That is a really good tutorial.
A must read post!