Nowadays the web users are not interested in filling 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 sign 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 the files structure.
facebook_login_php/ ├── config.php ├── index.php ├── logout.php ├── User.class.php ├── facebook-php-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 Facebook Developers Dashboard.
Go to the Settings » Basic page, note the App ID and App Secret. This App ID and App secret allow you to access the Facebook APIs.
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 retrieve the user’s Facebook timeline link and gender, you need to submit a request for user_link and user_gender permissions.
user_link
and user_gender
permissions and submit the required information.
Once the review process is completed and approved by the Facebook, you will be able to get the user profile link and gender from the Facebook Graph API.
Do you want a detailed guide on Facebook App creation? Go through this guide to create Facebook Developer App and get the App ID & App secret.
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` enum('facebook','google','twitter','') COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
`oauth_uid` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
`first_name` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
`last_name` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
`email` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
`gender` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL,
`picture` varchar(200) COLLATE utf8_unicode_ci NOT NULL,
`link` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
`created` datetime NOT NULL,
`modified` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
The facebook-php-graph-sdk/ directory contains the latest version (v5) of Facebook SDK for PHP. 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.
The User class handles the database related operations (connect, insert, and update) using PHP and MySQL. It helps to connect to the database and insert/update Facebook account data in the users table.
<?php
/*
* User Class
* This class is used for database related (connect, insert, and update) operations
* @author CodexWorld.com
* @url http://www.codexworld.com
* @license http://www.codexworld.com/license
*/
class User {
private $dbHost = DB_HOST;
private $dbUsername = DB_USERNAME;
private $dbPassword = DB_PASSWORD;
private $dbName = DB_NAME;
private $userTbl = DB_USER_TBL;
function __construct(){
if(!isset($this->db)){
// Connect to the database
$conn = new mysqli($this->dbHost, $this->dbUsername, $this->dbPassword, $this->dbName);
if($conn->connect_error){
die("Failed to connect with MySQL: " . $conn->connect_error);
}else{
$this->db = $conn;
}
}
}
function checkUser($data = array()){
if(!empty($data)){
// Check whether the user already exists in the database
$checkQuery = "SELECT * FROM ".$this->userTbl." WHERE oauth_provider = '".$data['oauth_provider']."' AND oauth_uid = '".$data['oauth_uid']."'";
$checkResult = $this->db->query($checkQuery);
// Add modified time to the data array
if(!array_key_exists('modified',$data)){
$data['modified'] = date("Y-m-d H:i:s");
}
if($checkResult->num_rows > 0){
// Prepare column and value format
$colvalSet = '';
$i = 0;
foreach($data as $key=>$val){
$pre = ($i > 0)?', ':'';
$colvalSet .= $pre.$key."='".$this->db->real_escape_string($val)."'";
$i++;
}
$whereSql = " WHERE oauth_provider = '".$data['oauth_provider']."' AND oauth_uid = '".$data['oauth_uid']."'";
// Update user data in the database
$query = "UPDATE ".$this->userTbl." SET ".$colvalSet.$whereSql;
$update = $this->db->query($query);
}else{
// Add created time to the data array
if(!array_key_exists('created',$data)){
$data['created'] = date("Y-m-d H:i:s");
}
// Prepare column and value format
$columns = $values = '';
$i = 0;
foreach($data as $key=>$val){
$pre = ($i > 0)?', ':'';
$columns .= $pre.$key;
$values .= $pre."'".$this->db->real_escape_string($val)."'";
$i++;
}
// Insert user data in the database
$query = "INSERT INTO ".$this->userTbl." (".$columns.") VALUES (".$values.")";
$insert = $this->db->query($query);
}
// Get user data from the database
$result = $this->db->query($checkQuery);
$userData = $result->fetch_assoc();
}
// Return user data
return !empty($userData)?$userData:false;
}
}
The database settings and Facebook API configuration constant variables are defined in the config.php
file.
Database Constants:
Facebook API Constants:
Call Facebook API:
<?php /* * Basic Site Settings and API Configuration */ // Database configuration define('DB_HOST', 'MySQL_Database_Host'); define('DB_USERNAME', 'MySQL_Database_Username'); define('DB_PASSWORD', 'MySQL_Database_Password'); define('DB_NAME', 'MySQL_Database_Name'); define('DB_USER_TBL', 'users'); // Facebook API configuration define('FB_APP_ID', 'Insert_Facebook_App_ID'); define('FB_APP_SECRET', 'Insert_Facebook_App_Secret'); define('FB_REDIRECT_URL', 'Callback_URL'); // Start session if(!session_id()){ session_start(); } // Include the autoloader provided in the SDK require_once __DIR__ . '/facebook-php-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.
In this file, the Facebook API authentication process is handled using PHP.
<?php
// Include configuration file
require_once 'config.php';
// Include User class
require_once 'User.class.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: ./');
}
// Getting user's 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();
// Redirect user back to app login page
header("Location: ./");
exit;
} catch(FacebookSDKException $e) {
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
// Initialize User class
$user = new User();
// 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']:'';
$fbUserData['picture'] = !empty($fbUser['picture']['url'])?$fbUser['picture']['url']:'';
$fbUserData['link'] = !empty($fbUser['link'])?$fbUser['link']:'';
// Insert or update user data to the database
$fbUserData['oauth_provider'] = 'facebook';
$userData = $user->checkUser($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)){
$output = '<h2>Facebook Profile Details</h2>';
$output .= '<div class="ac-data">';
$output .= '<img src="'.$userData['picture'].'"/>';
$output .= '<p><b>Facebook ID:</b> '.$userData['oauth_uid'].'</p>';
$output .= '<p><b>Name:</b> '.$userData['first_name'].' '.$userData['last_name'].'</p>';
$output .= '<p><b>Email:</b> '.$userData['email'].'</p>';
$output .= '<p><b>Gender:</b> '.$userData['gender'].'</p>';
$output .= '<p><b>Logged in with:</b> Facebook</p>';
$output .= '<p><b>Profile Link:</b> <a href="'.$userData['link'].'" target="_blank">Click to visit Facebook page</a></p>';
$output .= '<p><b>Logout from <a href="'.$logoutURL.'">Facebook</a></p>';
$output .= '</div>';
}else{
$output = '<h3 style="color:red">Some problem occurred, please try again.</h3>';
}
}else{
// Get login url
$permissions = ['email']; // Optional permissions
$loginURL = $helper->getLoginUrl(FB_REDIRECT_URL, $permissions);
// Render Facebook login button
$output = '<a href="'.htmlspecialchars($loginURL).'"><img src="images/fb-login-btn.png"></a>';
}
?>
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>Login with Facebook using PHP by CodexWorld</title>
<meta charset="utf-8">
</head>
<body>
<div class="container">
<div class="fb-box">
<!-- Display login button / Facebook profile information -->
<?php echo $output; ?>
</div>
</div>
</body>
</html>
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']); // Remove user data from session unset($_SESSION['userData']); // Redirect to the homepage header("Location:index.php"); ?>
Login with Facebook in CodeIgniter
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.
Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request
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.php
file and modify the$dbServer
,$dbUsername
,$dbPassword
,$dbName
variables 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.php
file and change the$homeurl
variable 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
email
string into the$fbPermissions
variable, not your email ID. Don’t change the$fbPermissions
value, 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.php
file. Probably the$appId
and$appSecret
does 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.php
file 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 ?