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
hello Sir, Thanks now its working fine …:)
hii i am able to login with your code but values not stored in database . i am using it on my server. no values inserted in database. could you please help me to solve this. Thanks in advance.
@Raman You need to change the database configuration settings as per your database credentials. Open the
includes/functions.phpfile and modify the$dbServer,$dbUsername,$dbPassword,$dbNamevariables value with your phpMyAdmin details.how get Facebook App Secret ?
@Santosh You can get the step-by-step guide to creating Facebook App, App ID, and App Secret from here – http://www.codexworld.com/create-facebook-app-id-app-secret
How can I get user’s facebook profile url?
@John Concat the profile ID with
https://www.facebook.com/. As per our script you can get Facebook profile URL by using the following line.Any way to integrate taggable_friends into permissions. I did on the app interface. $fbPermissions=’taggable_friends’ not working. Want to API call for taggable_friends array. Thanks so much for this code – working well – just need to build out this permission.
hi really excellent posting i used the code everything working fine, but there is a big problem with redirection issue, after login successfully, how can we redirect to page we want
@Mahendra Open the
config.phpfile and change the$homeurlvariable value with your desired redirect URL after login success.Awesome Tutorial. So Simplified.
yes i face the same problem that @raja said (the session contiues after i unset the session also.pls help me) please help us both!!!
Great and awesome tutorial. I want Pop up as Facebook Login Integration. In your tutorial, session can not destroy, it redirect with same user panel when i want to logout. Please figure out this problem soon. Thanks,
Hello sir , first of let me tell you , i have become a big fan of yours , sir i have been trying this since last three days and got no result but as i tried your codes bingo in the first attempt everything done .
sir now m gonna follow all your blogs . thank you so much sir
@Codexworld Great Tutorial but i have one additional implementation Now authentication URL is go to facebook website directly .i want that if user click on “Login with facebook” button one POP up should be open and there facebook authentication. I want to just do that authentication on different POP. ONCE user allow from facebook pop should be closed and user is redirected to our application successfully. please help me as soon as possible.Thanks in Advance………………
it is really a useful tutorial for me.i really thankful for you .but the logout is not working properly .the session contiues after i unset the session also.pls help me
Can it be done using code igniter?
@Rajiv We’ll try to publish the same for CodeIgniter soon.
Hii , thanks for this blog
But i am getting this message as error “Invalid Scope: rrrajiv8@gmail.com” whenever i click on login button
@Rajiv You only need to insert the
emailstring into the$fbPermissionsvariable, not your email ID. Don’t change the$fbPermissionsvalue, just leave as it is.This is not working in Facebook Canvas
Hello best tutorial…thank you 🙂
Hello. That’s great works. I would like get new permissions. How change it? (for example: user_friends_list)
I see you are using Facebook SDK 3.0
Could you make a tutorial for the 5.0?
Hello codex-world…need to about how to destroy facebook session for this code.
thank you my dear very nice tutorial … how to share or post my website any picture in facebook …please teach me if u have this tutorial please give this link ..thank u so much
account.php file missing plz upload
@Shweta In our latest version, account.php file is not needed.
Mate …. I owe you a beer! Really <3
Is it possible to fetch the timeline data OR public status data and store it in database like MySQL?
Thank you very much. It is easy and good.
hallo,
Worked for me fine too. Thanks
I,ve only 1 request: is it possible to open facebook login page in a popup insted of full browser page?
Thank you in advance for your answer.
Nice tutorial Sir….
Thank You Very much now its working fine…
pls upload the same thing for gmail login
@Ankur We’ve already published Login with Google account using PHP tutorial. Please check it out and give your feedback.
thanks sir it is working on my localhost. But please tell me if i want to make it live then what will be the value of app domain.
hello ,
I have set up in local and also change url in app domain still having issue that after login link redirect to homeurl and doesnt get fb profile details as it is in loop if(!fbuser) in index.php.. i checked twice everyting inspite of not solved. Can you please help me.
@Mitali Check defined Facebook App credentials in the
config.phpfile. Probably the$appIdand$appSecretdoes not matched with your Facebook App credentials.how to get profile image in good resolution
coz it’s just an logo image
how to make it size
i mean how to fetch it
@Anurag
Open the
index.phpfile and set the profile picture dimension by using the following line of code.You can set width and height of the profile picture as per your need. But facebook doesn’t return the exact size, It returns the closest dimension picture available with them.
Awesome tutorial. Thanks!
How to get password?? this project not getting password
So simple, so elegant ! big thanks I’ll try to integrate it now.
it works fine
and successfully
thanx for giving most usable information
Worked for me fine. Thanks
Really this article helped me a lot. thanks.
Useful post, definitely helps a lot….
its my first experience. thanks a lot. i tried many times on another websites but not successfull. a simple descricption on your site thanks again
Hi .. Thanks for this tutorial. It working fine but I have a problem, after logout only the local session value is destroy but facebook session is still active. Please help me…!
Thanks
Please help me..! After i host the website on a web server and change the facebook app settings also data won’t enter to the sql server. please help me. localhost its working but when i host its not working.
@Gihantwister You need to add the web server domain into the Facebook App Domains and modify the Site URL with your website URL.
Hi .. Thanks for this tutorial . I just want to know how should I register the user in database in case user email is not available ?