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
$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,
$fbUserProfile
array 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.php
file.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!