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
Hi I have added $loginUrl = $helper->getLoginUrl( array(‘scope’ => ’email’)); in fbconfig file and also found an option to allow email, but still not getting email in $graphObject variable please help
Model Is Deprecated Use as a basis and require in controller ex{ require ‘dbconfig.php’; }
prepare(‘SELECT * from Users WHERE Fuid = :fuid’);
$check->bindParam(‘:fuid’, $fuid);
$check->execute();
$results = $check->fetchAll();
if (count($results) == 0 ) {
$stmt = $dbh->prepare(“INSERT INTO Users (Fuid,Ffname,Femail) VALUES (:fuid, :ffname, :femail);”);
$stmt->bindParam(‘:fuid’, $fuid);
$stmt->bindParam(‘:ffname’, $ffname);
$stmt->bindParam(‘:femail’, $femail);
$stmt->execute();
}else{
if ($results[0][‘Fuid’] !== $fuid) {
$stmt = $dbh->prepare(“INSERT INTO Users (Fuid,Ffname,Femail) VALUES (:fuid, :ffname, :femail);”);
$stmt->bindParam(‘:fuid’, $fuid);
$stmt->bindParam(‘:ffname’, $ffname);
$stmt->bindParam(‘:femail’, $femail);
$stmt->execute();
}else{
$stmt = $dbh->prepare(“UPDATE Users SET Ffname=:ffname, Femail=:femail where Fuid=:fuid”);
$stmt->bindParam(‘:fuid’, $fuid);
$stmt->bindParam(‘:ffname’, $ffname);
$stmt->bindParam(‘:femail’, $femail);
$stmt->execute();
}
}
}
?>
using this script can we post on users time line please help i got error
Fatal error: Uncaught exception ‘FacebookFacebookPermissionException’ with message ‘(#200) The user hasn’t authorized the application to perform this action’ in
$session = $helper->getSessionFromRedirect();
why session empty ??
Given URL is not permitted by the Application configuration: One or more
of the given URLs is not permitted by the App’s settings. It must match
the Website URL or Canvas URL, or the domain must be a subdomain of one
of the App’s domains.
Anyone know why I would be getting a 500 Internal Server Error? I uploaded the demo file to my hosting account and that’s the error I get when I click the Facebook login.
great! but no data is being saved in my database although as you described.
Did you find the solution to save the data in your database ?
It is a good script but i have a problem whenever i click on login button it just takes me to fbconfig.php page and stop plzz suggest somthing
Very helpfull
i get only full name and facebook id, not the email. I need permission using scope partameter. But where to include that FB.login()…………. code?
how did you get full name ?? not working with me … thanks
$fbfullname = $graphObject->getProperty(‘name’);
Same here. Email is always blank. I went into my FB account and tried making it visible to the public too.
email not working also… my other script worked… I will go back to that, thought this was simpler but if it does not work, then the simplicity is useless
Hola! can you send the link of the previous version that you are using? I have php 4.9 and 5.2 and need something older…
this worked for me by changing the the loginURL scope:
else {
$loginUrl = $helper->getLoginUrl(array(
‘scope’ => ’email’
));
header(“Location: “.$loginUrl);
}
Anybody else having problem withe the email????????????
PLEASE HELP HERE!
Hai I am working with this script. It is very nice article. The problem is in this code email is not getting. I want Mobile number and email id of login users. Is it possible? please help me
update this line on index $helper->getLoginUrl(array(’email’))
Hi I have added $loginUrl = $helper->getLoginUrl( array(‘scope’ => ’email’)); in fbconfig file and also found an option to allow email, but still not getting email in $graphObject variable please help
thanks for tutorial ,it’s working fine for me ,but the issue is i m nt getting user email,plz help,,thanks in advance…!
3 people have answered this now. Read the comments and you’ll get your answer
how to fetch the name of friend list from facebook
Hey, did you find a solution ?
hope this helping: $loginUrl = $helper->getLoginUrl(array(‘scope’ => ’email, public_profile,user_friends’));
Has anyone figured out how to retreive the email into the $graphObject object?
alter yours to this: $loginUrl = $helper->getLoginUrl(array(‘scope’ => ’email, public_profile,user_friends’));
hi,this is working fine but it will not return email address . so how i got email address for login user ? help me .
try this: $loginUrl = $helper->getLoginUrl(array(‘scope’ => ’email, public_profile,user_friends’));
i didn’t get facebook email with is plugin
try alter your code to this: $loginUrl = $helper->getLoginUrl(array(‘scope’ => ’email, public_profile,user_friends’));
I using $loginUrl = $helper->getLoginUrl(array(
‘scope’ => ’email’
));
header(“Location: “.$loginUrl);
I can’t read email of user. Please help me. My app id: 618088084999378, app secret: 47279391f70fb1c6028c6212a8a5f34f
if someone still need to get email or other data… I just found solution..
where is line “$request = new FacebookRequest( $session, ‘GET’, ‘/me’ );”
add to URL address more fields like this:
“$request = new FacebookRequest( $session, ‘GET’, ‘/me?locale=en_US&fields=first_name,last_name,email’ );”
HI, I have followed your line of code but there was not email returning. Do you have other solution?
do you have any solution of this? w have same thing, i followed this line of code and nothing … :/
$loginUrl = $helper->getLoginUrl(array(‘scope’ => ’email, public_profile,user_friends’));
if someone still need to get email or other data… I just found solution..
where is line “$request = new FacebookRequest( $session, ‘GET’, ‘/me’ );”
add to URL address more fields like this:
“$request = new FacebookRequest( $session, ‘GET’, ‘/me?locale=en_US&fields=first_name,last_name,email’ );”
DUDE YOU ARE SO AWESOME THANKS!
lol..it’s been posted 2x now above 🙂 He is the 3rd awesomest person
Notice: Undefined index: FBID in C:xampphtdocsiniciarfbindex.php on line 11
11
ayuda porfa 🙁
Notice: Undefined index: FBID in C:xampphtdocsiniciarfbindex.php on line 11
11
please help 🙁
11
Notice: Undefined index: FBID in C:xampphtdocsiniciarfbindex.php on line 11
please help 🙁
esta linea me marca error
Notice: Undefined index: FBID in C:xampphtdocsiniciarfbindex.php on line 11
ayuda porfavor 🙁
php if ($_SESSION[‘FBID’]):
php if ($_SESSION[‘FBID’]):
Notice: Undefined index: FBID in C:xampphtdocsiniciarfbindex.php on line 11
alguien puede ayudarme 🙁
logout not working
code not working it shows error abou FBID please give correct zip file
How can i get about_me information of an user. My app is approved for this info.