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
I can not take my files, because your site will not generate a link for dovnload
please try now .. sorry for the late reply
in database records are not inserted and after login it returns back home page…..database is empty please help me out
when i login i my account in facebook it will redirect into my index file and i cannot see my information in my facebook
same problem i found
I can not take my files, because your site will not generate a link for dovnload
please try now .. sorry for the late reply
in database records are not inserted and after login it returns back home page…..database is empty please help me out
when i login i my account in facebook it will redirect into my index file and i cannot see my information in my facebook
same problem i found
I cannot download the files. Where can I get the base_facebook.php and facebook.php scripts
I cannot download the files. Where can I get the base_facebook.php and facebook.php scripts
Hey, nice script, but could you modify it to just logout from the website and not distroing whole session and logging you out from facebook too?
ubnhjb
Hey, nice script, but could you modify it to just logout from the website and not distroing whole session and logging you out from facebook too?
ubnhjb
Thank you very much. That’s really help me.
Thank you very much. That’s really help me.
Awesome man, you did a great job…it reeally helped it out.
Awesome man, you did a great job…it reeally helped it out.
after login i want it is to be redirected to some other page, for that how will i do it
in fbconfig.php ..
$loginUrl = $facebook->getLoginUrl(array(
‘scope’ => ’email’, // Permissions to request from the user
‘redirect_uri’ => ‘https://https://www.krizna.com/general/login-with-facebook-using-php/’ // redirect url after login
));
how to get friend list & friend’s email id of user who is login through ur script
after login i want it is to be redirected to some other page, for that how will i do it
in fbconfig.php ..
$loginUrl = $facebook->getLoginUrl(array(
‘scope’ => ’email’, // Permissions to request from the user
‘redirect_uri’ => ‘https://http://www.krizna.com/general/login-with-facebook-using-php/’ // redirect url after login
));
how to get friend list & friend’s email id of user who is login through ur script
In functions.php you have this:
$check = mysql_query(“select * from Users where Fuid=’$fbid'”);
$check = mysql_num_rows($check);
if (empty($check)) {
The variable $check make redundancy and put two records duplicated into the database, I´m fixing with this
$check = mysql_query(“select * from Users where Fuid=’$fbid'”);
$counter = mysql_num_rows($check);
if ($counter > 0) {
I´am not sure using empty function because empty return true if de the variable is declared or have the value 0
@isaacfraireheredia:disqus
$check = mysql_num_rows($check);
//if new user.. $check will be 0 since it will not find any record and below condition will be true .. it ill insert new record ( new user )
if (empty($check)) {
Now check yours
$counter = mysql_num_rows($check);
//if new user .. $check will be 0 .. and below condition will be false .. no record inserted..
if ($counter > 0) {
hope this helps u
@isaacfraireheredia:disqus
$check = mysql_num_rows($check);
//if new user.. $check will be 0 since it will not find any record and below condition will be true .. it ill insert new record ( new user )
if (empty($check)) {
Now check yours
$counter = mysql_num_rows($check);
//if new user .. $check will be 0 .. and below condition will be false .. no record inserted..
if ($counter > 0) {
hope this helps u
Nice script, but i have a problem with this. : when I log in it works. when I click logout, I get on other side I have defined in fbconfig.php. is ok.
but. when I open a the domain in a new brwoser windows, then I’m logged in. logout not working for me.
if I completely close the browser, and re-open broser, I am logged out .
please help me 🙂
OMG … error found ^^
this is your code :
$facebook->destroySession();
and this is my code:
$facebook->distroySession();
ok now it working perfect ..
thx for the script
where is this code?
I can’t find 🙁
Hi, Nika I have an issue “This webpage has a redirect loop” can you help me regarding this. I will be thankful.
Nice script, but i have a problem with this. : when I log in it works. when I click logout, I get on other side I have defined in fbconfig.php. is ok.
but. when I open a the domain in a new brwoser windows, then I’m logged in. logout not working for me.
if I completely close the browser, and re-open broser, I am logged out .
please help me 🙂
OMG … error found ^^
this is your code :
$facebook->destroySession();
and this is my code:
$facebook->distroySession();
ok now it working perfect ..
thx for the script
where is this code?
I can’t find 🙁
Hi, Nika I have an issue “This webpage has a redirect loop” can you help me regarding this. I will be thankful.
Hi, am having the same problem.I can logout from my website but if i open facebook in new tab i still have a session.I want to kill all facebook session on logout.Thanks for this great piece of code
I am facing an error that is->Given URL is not allowed by the Application configuration.: One or more
of the given URLs is not allowed 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.
how can i solve this
Make sure to add platform before adding the url, to avoid the error
I am facing an error that is->Given URL is not allowed by the Application configuration.: One or more
of the given URLs is not allowed 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.
how can i solve this
Make sure to add platform before adding the url, to avoid the error
if($user) condition false.
if($user) condition false.
but i got error is “Given URL is not allowed by the Application configuration.: One or more
of the given URLs is not allowed 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.” how can i solve this?
have to make sure your domain name and the domain in the app settings on facebook match, inclusing the subdomain or www. part(if you have qwerty.com on one and type http://www.qwerty.com in the other , it wont work) for same reason it doesn’t work on a localhost unless there is a workaround
Make sure you set the site url on the app dashboard on facebook
but i got error is “Given URL is not allowed by the Application configuration.: One or more
of the given URLs is not allowed 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.” how can i solve this?
have to make sure your domain name and the domain in the app settings on facebook match, inclusing the subdomain or www. part(if you have qwerty.com on one and type http://www.qwerty.com in the other , it wont work) for same reason it doesn’t work on a localhost unless there is a workaround
Make sure you set the site url on the app dashboard on facebook
I have the same issue please help us
hey admin not worked in my project?? 🙁
hey admin not worked in my project?? 🙁
Bro, thanks a lot for this. Very helpful. I’d like to just point out that this code is no longer working. But just add that big ass fb_ca_chain_bundle.crt file in the src folder and it works…but it’s not recognizing the username attribute anymore among the user details.
Bro, thanks a lot for this. Very helpful. I’d like to just point out that this code is no longer working. But just add that big ass fb_ca_chain_bundle.crt file in the src folder and it works…but it’s not recognizing the username attribute anymore among the user details.
Nice job. In my case, the variable $funame is not getting the username from facebook through $fbuname = $user_profile[‘username’]; The other vars are getting the right. Any guess?
same on my case bro what to do?
Nice job. In my case, the variable $funame is not getting the username from facebook through $fbuname = $user_profile[‘username’]; The other vars are getting the right. Any guess?
same on my case bro what to do?
Just remove USERNAME and replace it with FULLNAME
How can one see all the variables we can fetch? I see code that looks different indicating you can get Gender, location, birthday, etc. When I try adding those following similar code style as what works for FULLNAME.
place this in ur username add fullname
I cannot log out 🙁
probably same issue, if i click logout it logs me out of facebook, but i stay logged in the website using this script with full access to my fb data.(just using vanilla copy of script atm). any suggestions?
only way i seem to be able to revoke access to profile is to remove app in my facebook settings. bit problem, since if someone logs into my site on a PC, then logs out, someone else comes on PC – they immediately get access to previous account since logout doesn’t work and they can see all previous users fb details displayed, without even needing a fb login :/ googling fix now, but thus far seems noone else has/has noticed this issue :(… search continues…
Same issue here. Fixed.
Go to index.php page. Replace the logout link with the following link:
Logout
go to logout.php and change the header location to your desired url.
madam, can you help me, I have ”
This webpage has a redirect loop” issue coming up. thanks.