Login with facebook : You can use facebook login in your websites to allow users to login using their facebook account.you don’t need an extra registration and user management for your sites.you can also manage users in your facebook application page. This article explains how to integrate “Facebook login” to your websites using Facebook PHP SDK with an example and demo.
Login with facebook ( Version: 4 – Updated )
Create Facebook APP ID and APP secret .
Step 1 » Goto https://developers.facebook.com/apps/ and Click Add a New App .
» Choose Website
» Choose Name for you App and Click Create New Facebook App ID
» Choose a category for you App and click Create App ID
» Now Click Skip Quick Test
Step 2 » Under settings, Provide values for App domain ( Eg:www.krizna.com ) and Contact Email and click Add Platform.
Provide Values for Site URL and Mobile site URl ( Optional )
Step 3 » Now under Status & Review, Click the button to make you App live .
fbconfig.php file overview
Step 4 » Download the Demo package here Login with facebook .
Step 5 » Now open fbconfig.php file and enter your app ID, secret and change domain name .
// init app with app id and secret FacebookSession::setDefaultApplication( '64296382121312313','8563798aasdasdasdweqwe84' ); // login helper with redirect_uri $helper = new FacebookRedirectLoginHelper('https://www.krizna.com/fbconfig.php' );
Step 6 » Finally full code of fbconfig.php file. See the commented lines for more details
<?php session_start(); // added in v4.0.0 require_once 'autoload.php'; //require 'functions.php'; use FacebookFacebookSession; use FacebookFacebookRedirectLoginHelper; use FacebookFacebookRequest; use FacebookFacebookResponse; use FacebookFacebookSDKException; use FacebookFacebookRequestException; use FacebookFacebookAuthorizationException; use FacebookGraphObject; use FacebookEntitiesAccessToken; use FacebookHttpClientsFacebookCurlHttpClient; use FacebookHttpClientsFacebookHttpable; // init app with app id and secret FacebookSession::setDefaultApplication( '64296382121312313','8563798aasdasdasdweqwe84' ); // login helper with redirect_uri $helper = new FacebookRedirectLoginHelper('https://www.krizna.com/fbconfig.php' ); try { $session = $helper->getSessionFromRedirect(); } catch( FacebookRequestException $ex ) { // When Facebook returns an error } catch( Exception $ex ) { // When validation fails or other local issues } // see if we have a session if ( isset( $session ) ) { // graph api request for user data $request = new FacebookRequest( $session, 'GET', '/me' ); $response = $request->execute(); // get response $graphObject = $response->getGraphObject(); $fbid = $graphObject->getProperty('id'); // To Get Facebook ID $fbfullname = $graphObject->getProperty('name'); // To Get Facebook full name $femail = $graphObject->getProperty('email'); // To Get Facebook email ID /* ---- Session Variables -----*/ $_SESSION['FBID'] = $fbid; $_SESSION['FULLNAME'] = $fbfullname; $_SESSION['EMAIL'] = $femail; //checkuser($fuid,$ffname,$femail); header("Location: index.php"); } else { $loginUrl = $helper->getLoginUrl(); header("Location: ".$loginUrl); } ?>
logout.php file overview
Logout.php file is used only to destroy facebook session and return back to your home page .
Step 7 » Enter your home page in the code to redirect after logout.
<?php session_start(); session_unset(); $_SESSION['FBID'] = NULL; $_SESSION['FULLNAME'] = NULL; $_SESSION['EMAIL'] = NULL; header("Location: index.php"); // you can enter home page here ( Eg : header("Location: " ."https://www.krizna.com/home.php"); ?>
index.php file overview
Step 8 » You can change this file as per your need . Split this file into 2 parts before login and after login.
<?php session_start(); ?> <!doctype html> <html xmlns:fb="http://www.facebook.com/2008/fbml"> <head> <title>Login with facebook</title> --- --- --- css stuff --- --- ---- </head> <body> <?php if ($_SESSION['FBID']): ?> -- --- - - - -- - Display content After user login -- -- - --- ---- -- - <?php else: ?> -- --- - - - -- - Display content before login -- -- - --- ---- -- - <?php endif ?> </body> </html>
Finally full code of index.php file .
<?php session_start(); ?> <!doctype html> <html xmlns:fb="http://www.facebook.com/2008/fbml"> <head> <title>Login with Facebook</title> <link href="http://www.bootstrapcdn.com/twitter-bootstrap/2.2.2/css/bootstrap-combined.min.css" rel="stylesheet"> </head> <body> <?php if ($_SESSION['FBID']): ?> <!-- After user login --> <div class="container"> <div class="hero-unit"> <h1>Hello <?php echo $_SESSION['USERNAME']; ?></h1> <p>Welcome to "facebook login" tutorial</p> </div> <div class="span4"> <ul class="nav nav-list"> <li class="nav-header">Image</li> <li><img src="https://graph.facebook.com/<?php echo $_SESSION['USERNAME']; ?>/picture"></li> <li class="nav-header">Facebook ID</li> <li><?php echo $_SESSION['FBID']; ?></li> <li class="nav-header">Facebook fullname</li> <li><?php echo $_SESSION['FULLNAME']; ?></li> <div><a href="logout.php">Logout</a></div> </ul></div></div> <?php else: ?> <!-- Before login --> <div class="container"> <h1>Login with Facebook</h1> Not Connected <div> <a href="fbconfig.php">Login with Facebook</a></div> </div> <?php endif ?> </body> </html>
That’s it . now facebook users can login into your websites using facebook login ID.
Store the User information
» You can store the user info locally . Create a mysql database and import below table structure .
CREATE TABLE IF NOT EXISTS `Users` ( `UID` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `Fuid` varchar(100) NOT NULL, `Ffname` varchar(60) NOT NULL, `Femail` varchar(60) DEFAULT NULL, PRIMARY KEY (`UID`) );
» Open dbconfig.php file and change the DB vlaues.
<?php define('DB_SERVER', 'localhost'); define('DB_USERNAME', 'username'); // DB username define('DB_PASSWORD', 'password'); // DB password define('DB_DATABASE', 'database'); // DB name $connection = mysql_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD) or die( "Unable to connect"); $database = mysql_select_db(DB_DATABASE) or die( "Unable to select database"); ?>
» functions.php file contains a function to update the user information .
<?php require 'dbconfig.php'; function checkuser($fuid,$ffname,$femail){ $check = mysql_query("select * from Users where Fuid='$fuid'"); $check = mysql_num_rows($check); if (empty($check)) { // if new user . Insert a new record $query = "INSERT INTO Users (Fuid,Ffname,Femail) VALUES ('$fuid','$ffname','$femail')"; mysql_query($query); } else { // If Returned user . update the user record $query = "UPDATE Users SET Ffname='$ffname', Femail='$femail' where Fuid='$fuid'"; mysql_query($query); } } ?>
» Uncomment the below lines in fbconfig.php
require 'functions.php'; // Include functions
checkuser($fbid,$fbfullname,$femail); // To update local DB
That’s it .. now you can store the values locally .
Download contains all the configuration files .
Good luck
Fak
not at all
this is test by kunal
when I enter username and password into facebook I got this error
App Not Setup: 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.
1 – Check the “Settings” the URL of the site you entered must be the same that is testing
2 – then “Application Review”, make it public
I am used Facebook login its successed but I can’t get email. How can I get email?? The older version I Got all details but new version i can’t. If any solution please help Its urgent
same problem
i have same problems
try these changes in fbconfig.php
it worked for me…..
if ( isset( $session ) ) {
FROM —
$request = new FacebookRequest( $session, ‘GET’, ‘/me’ );
TO —
$request = new FacebookRequest( $session, ‘GET’, ‘/me?fields=name,email’);
…
…
…
..
…
} else {
FROM —
$loginUrl = $helper->getLoginUrl();
TO —
$loginUrl = $helper->getLoginUrl(array(‘scope’ => ’email’));
…
…
}
how to fetch facebook friend list
Try this –
$request = new FacebookRequest( $session, ‘GET’, ‘/me/friends’ );
I got the email with the change in the 1st half of your example (also mentioned above by another user), but what is the else code needed for?
In else code –
i’m asking for “Email Permission” by using scope in login URL.
I am used Facebook login its successed but I can’t get frinds
I can’t get mobile no.
https://developers.facebook.com/docs/graph-api/reference/user
Here is the list of parameters that you can access from Facebook API. you can not get information (mobile number or address) out of this list. Hope this helps.
No you can’t get mobile number or address as its been disabled developer access to mobile number and address by Facebook. hope this helps.
Try Following
$request = new FacebookRequest( $session, ‘GET’, ‘/me/friends’ );
Hope this helps.
@Harshil @harshilparmar:disqus
Thanks a lot
Uncaught exception ‘Exception’ with message ‘Facebook needs the CURL PHP
extension.’ in
C:xampphtdocsshubhamfacebook_login_with_phpincbase_facebook.php:19
Stack trace:
#0 C:xampphtdocsshubhamfacebook_login_with_phpincfacebook.php(18):
require_once()
#1 C:xampphtdocsshubhamfacebook_login_with_phpconfig.php(2):
include_once(‘C:xampphtdocs…’)
#2 C:xampphtdocsshubhamfacebook_login_with_phpindex.php(2):
include_once(‘C:xampphtdocs…’)
#3 {main}
thrown in C:xampphtdocsshubhamfacebook_login_with_phpincbase_facebook.php on line 19
How to solve it
Hello, I am facing this error.
Parse error: syntax error, unexpected T_STRING, expecting T_CONSTANT_ENCAPSED_STRING or ‘(‘ in D:AppServwwwfbfbconfig.php on line 7
use FacebookFacebookSession; //line 7
use FacebookFacebookRedirectLoginHelper;
use FacebookFacebookRequest;
use FacebookFacebookResponse;
use FacebookFacebookSDKException;
use FacebookFacebookRequestException;
use FacebookFacebookAuthorizationException;
use FacebookGraphObject;
use FacebookGraphUser;
use FacebookGraphSessionInfo;
use FacebookHttpClientsFacebookHttpable;
use FacebookHttpClientsFacebookCurlHttpClient;
use FacebookHttpClientsFacebookCurl;
Anybody let me know why I am getting this error.
I think there is a PHP version error.
Namespace support require PHP 5.3 or later.
check out this link
http://stackoverflow.com/questions/13960277/error-parse-error-syntax-error-unexpected-t-string-expecting-t-constant-encap
i think this is a PHP version error
because namespace support require PHP 5.3 or later
check out this link
http://stackoverflow.com/questions/13960277/error-parse-error-syntax-error-unexpected-t-string-expecting-t-constant-encap
how to fetch mobile no
Please help… Redirection problem.
http://mob.iyanagames.com/1353/
As you solved it?
Please help ..this same problem
To store the information in my DB im told to uncomment require ‘functions.php’; and checkuser($fbid,$fbfullname,$femail); in the fbconfig.php file, but i can’t seem to locate those lines
Hi there, if you still have this problem, add those 2 lines as below.
And don’t forget to uncomment them.
require_once ‘autoload.php’;
//require ‘functions.php’;
use FacebookFacebookSession;
use FacebookFacebookRedirectLoginHelper;
……
$_SESSION[‘FBID’] = $fbid;
$_SESSION[‘FULLNAME’] = $fbfullname;
$_SESSION[‘EMAIL’] = $femail;
//checkuser($fbid,$fbfullname,$femail);
header(“Location: index.php”);
Thanks 🙂
The Facebook ID, name and email are not added to the MySQL db when following this tutorial. A row is created with the primary key, but the facebook data is never added. Any suggestions?
I’m just wondering since im a rookie – how is this functions.php file secured against SQL injection?
The email is doesn’t appear in info ? why ?
aaa
bbbb
Great post. But how I can getting the link of profile photo with
extension? Because the link ‘…/picture’ isn’t showing in site. I’m
sorry for my English.
Hi…! After i integrated it into my web it shows an error ( “Fatal error: Class ‘FacebookFacebookSession’ not found in C:xampphtdocshanufbconfig.php on line 18” ) Please send me the solution for this error…
thank you in advance…
Wonderful tutorial it is… Everything is working fine after integrating it into my web site but the values are not stored into my database table.
Please try provide solution for me…
thank you in advance..
Hello,,
I have used ur script but i m getting error.So I am sharing the image of error
the page is not redirecting..
it showing only facebook id and full name. not showing email id. can you plz help me on this.
Email ID? or Email? Getting the email has been explained 3x now above
how to save user profile picture in our local drive
Great tutorial. No issues following your instructions and getting it to work. Spent a lot of time with PHP v5 FB login examples and eventually got that working, but not how I wanted, and found the code far more confusing.
#1 – Could someone explain how to get other values/data from Facebook? $_SESSION[‘USERNAME’] doesn’t work as the code shows, and $_SESSION[‘EMAIL’] is blank, but I was trying to get $_SESSION[‘BIRTHDAY’], $_SESSION[‘GENDER’], location, dateAccountCreated, etc to work. As soon as I added these values to your code, the page stopped working without errors.
#2 – I dislike that I can’t test locally. Read some examples of how to test locally, but they failed. Anyone got it to work locally? It would help me to troubleshoot and speed up my work.
Thanks in advance for any help.
Thank you verry much
How can users login on your site using data from another website. for example I have to create a website where student will login using data from our university site, I mean instead of “login with google” or “login with facebook” they can be able to “login with university-data”.. How can I make this possible?
Nice article , this code 100% work.
thanks
Login with facebook using PHP ( Demo and Download ) with version 5.0 please.
I have a redirection problem, please help me!
Thank you very much for this wonderful article. It worked perfectly (after few email tweaks though). I wish to know how can i get the user’s address and mobile no details? What else should i pass in,
$request = new FacebookRequest( $session, ‘GET’, ‘/me?fields=id,name,email’);
to get the user’s address details. Any help will be highly appreciated!
Thanks in advance
it is not working still am facing Error….
Hola tengo u problema, cuando lo subo a un servidor me regresa un code=XXXXX por get pero no me ejecuta nada
i am being taken back to redirect url when i click on login with facebook.
please help . no insertion in db