Last week one of my reader asked me that how to Implement Facebook oAuth Login with Javascript SDK without Page Refresh and also data should be store on MYSQL server as well. So I thought this is the time to write a tutorial for this.
Facebook has several login methods based on the devices like iOS, Android and Web. Here we are going to Implement this Facebook oAuth login system for Website. Millions of Websites and Apps are implemented Facebook Login into their sites to increase the registrations. I hope this simple tutorial will help you to implement in your PHP web based projects 🙂
Contents
View Live Demo & Download
Please checkout my popular tutorial on How to create Mention system like Facebook & Twitter using PHP & jQuery
Step 1 – Creating Facebook App
We need to create an Facebook App to get the App ID and App Secret Key
Goto https://developers.facebook.com/apps/ and Click Add a New App
In the popup – click website
Now Click Skip Quick Test
You need to Choose Name for your App and Click Create App ID
Step 2 – App Settings
Under settings, Provide values for App domain ( Eg: w3lessons.info ) and Contact Email and click Save Changes. And Provide Values for Site URL and Mobile site URL ( Its Optional )
Step 3 – Making App Live
Now under Status & Review, Click the button to make you App live after you implemented the FB login in your project. In the meantime you can use your email ID for development/testing purposes
After creating the app, Please create the table called tbl_users in your database
CREATE TABLE IF NOT EXISTS `tbl_users` (
`fld_user_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`fld_facebook_id` varchar(100) NOT NULL,
`fld_user_name` varchar(60) NOT NULL,
`fld_user_email` varchar(60) DEFAULT NULL,
`fld_user_doj` int(10) NOT NULL,
PRIMARY KEY (`fld_user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
Facebook Javascript SDK
Please the below code on before body tag. The below script will load the SDK asynchronously
(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
Now we need to initialize the facebook javascript SDK
window.fbAsyncInit = function() {
FB.init({
appId : 'your app ID',
cookie : true, // enable cookies to allow the server to access
// the session
xfbml : true, // parse social plugins on this page
version : 'v2.3' // use version 2.3
});
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
});
};
In the above code, the FB.getLoginStatus function allows you to determine if a user is logged in to Facebook and has authenticated your app. There are three possible states for a user:
- the user is logged into Facebook and has authenticated your application (connected)
- the user is logged into Facebook but has not authenticated your application (not_authorized)
- the user is not logged into Facebook at this time and so we don’t know if they’ve authenticated your application or not (unknown)
With social application, knowing which of the these three states the user is in is one of the first things your application needs to know upon page load.
// This is called with the results from from FB.getLoginStatus().
function statusChangeCallback(response) {
if (response.status === 'connected') {
// Logged into your app and Facebook.
// we need to hide FB login button
$('#fblogin').hide();
//fetch data from facebook
getUserInfo();
} else if (response.status === 'not_authorized') {
// The person is logged into Facebook, but not your app.
$('#status').html('Please log into this app.');
} else {
// The person is not logged into Facebook, so we're not sure if
// they are logged into this app or not.
$('#status').html('Please log into facebook');
}
}
// This function is called when someone finishes with the Login
// Button. See the onlogin handler attached to it in the sample code below.
function checkLoginState() {
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
});
}
Facebook oAuth Login Call Function
The below code will be called after clicking the Login with Facebook button from the web app.
There is an optional scope parameter that can be passed along with the function call that is a comma separated list of permissions to request from the person using the app. Here’s how you would call FB.login() with the same scope as the Login Button we used below.
We need to call the FBLogin() while clicking the Login with Facebook button
function FBLogin()
{
FB.login(function(response) {
if (response.authResponse)
{
getUserInfo(); //Get User Information.
} else
{
alert('Authorization failed.');
}
},{scope: 'public_profile,email'});
}
The below getUserInfo() will be called after successful login with facebook. We are now ready to call the FB API calls via FB.api() method.
Syntax of FB.api()
FB.api('/me', function(response) {
console.log(JSON.stringify(response));
});
We need to pass the response to the php file where we can insert or update the user in our database.
function getUserInfo() {
FB.api('/me', function(response) {
$.ajax({
type: "POST",
dataType: 'json',
data: response,
url: 'check_user.php',
success: function(msg) {
if(msg.error== 1)
{
alert('Something Went Wrong!');
} else {
$('#fbstatus').show();
$('#fblogin').hide();
$('#fbname').text("Name : "+msg.name);
$('#fbemail').text("Email : "+msg.email);
$('#fbfname').text("First Name : "+msg.first_name);
$('#fblname').text("Last Name : "+msg.last_name);
$('#fbid').text("Facebook ID : "+msg.id);
$('#fbimg').html("<img src='http://graph.facebook.com/"+msg.id+"/picture'>");
}
}
});
});
}
The above function will return the data in JSON format. We need to parse and display those datas.
Logout from Facebook
You can log people out of your app by attaching the JavaScript SDK function FB.logout to a button or a link, as follows:
function FBLogout()
{
FB.logout(function(response) {
$('#fblogin').show(); //showing login button again
$('#fbstatus').hide(); //hiding the status
});
}
Below PHP code is used to update or insert the user in our database
check_user.php
if(isset($_POST['id']) && !empty($_POST['id']))
{
include_once 'db.php';
extract($_POST); // extract post variables
//check if facebook ID already exits
$check_user_query = "select * from tbl_users WHERE fld_facebook_id = $id";
$check_user = $db->getDataFromQuery($check_user_query);
if(!$check_user)
{
//new user - we need to insert a record
$time = time();
$insert_user_query = "Insert into tbl_users (`fld_user_name`, `fld_user_email`, `fld_facebook_id`, `fld_user_doj`) VALUES ('$name', '$email', $id, $time)";
$insert_user = $db->UpdateQuery($insert_user_query);
echo json_encode($_POST);
} else {
//update
$update_user_query = "update tbl_users set fld_user_name = '$name', fld_user_email='$email' WHERE fld_facebook_id = $id";
$update_user = $db->UpdateQuery($update_user_query);
echo json_encode($_POST);
}
} else {
$arr = array('error' => 1);
echo json_encode($arr);
}
Please dont forgot the check the live demo on Facebook oAuth Login with Ajax, PHP & MYSQL
Please subscribe to my blog to get the latest updates
View Live Demo & Download
just use for example josuepacheco1986@gmail.com from the comments :))))
Brilliant! Thank you sooo much!
Could you please update the database? Thanks 🙂
Update database please. But I’m subscribed and I can not downloading.
hi anybody how has the download files and is willing to share? email = amazinggrace911@hotmail.com
waiting for the download files bro.i subscribed but still it says no entry in database…its been around 48 hours.plz help
me too, also waiting for the files
Hi,
Please update the sub. database.
I am waitng for the download, n its been too long since i registered.
this one unfortunately does not work in chrome ios !
Hi Akin,
Could you please share the screenshot?
Thanks
Can you update registered sub, please?
Hey Man, can you update de registered sub??
Can you update registered sub, please?
Please update the registered sub 🙁
Please update the registered sub 🙁
please update the registered sub, I have two days and nothing, email maxlaren@hotmail.com
Hi Max,
Database has been updated.. Please download it from here http://demos.w3lessons.info/facebook-oauth2-login/
Sorry for the inconvenience
Thanks
Thanks 😀
Please send me download files. I registered my email 2days ago luisfernando@ribertech.com.br
Karthikeyan .. update the database please … it has been 24 hrs since i signed up or send me the code at amitsamota21@gmail.com
I subscribed to the mailing list 2 Hrs back, however download is still not working stating that email is not listed in database..plzz update database..
Hi Karthik, Could you please send me the codes: sagnik.pal@gmail.com;
I subscribed to the mailing list 24 Hrs back, however download is still not working stating that email is not listed in database.
Hi Sagnik,
Sorry for the Inconvenience caused.
I have updated the database now.. Please download it again
Thanks
Hi, Great tutorial, can you update subscriber database, I cant download. Thanks
hi how can i download it? i have register my email id and verified it and i can’t see any link to download your code.. pls help me
Hi Karthikeyan, Gr8 work… and thank you for sharing.
In the current version which i have downloaded, Upload picture doesn’t support multiple image upload? Can you fix this ?
still waiting the “subscriber” database update
what values store in $name,$email,$id variable ? Could you tell me.. and how to declare those variable with Facebook Name, Email, and ID in check_user.php
Hi dude,
i use script you it’s ok but …
Email : undefined
First Name : undefined
Last Name : undefined
in demo it show all data that work but i download and use it not show same demo.
how i can fix it ?
Thank you dude 😀
change line FB.api to FB.api(‘/me’, {fields: ‘id,name,email’}, function(response) {
Hey,
Can you please send the script. I have subscribed but not be able to download it.
Please send it at: josuepacheco1986@gmail.com
Hi Josué Pacheco,
I use this code getting i am name,email,id, profile picture etc.
First of all you will go to enable these are option from your facebook app setting.
https://developers.facebook.com/
You will read it Stackoverflow .
http://stackoverflow.com/questions/22266293/facebook-returns-undefined-for-email-and-birthday
Email : undefined
First Name : undefined
Last Name : undefined
how to fix this problem?
please guide for me
thank you
i got it
first name & last name i don’t need i add // for comment it
but i need email
i change line FB.api to FB.api(‘/me’, {fields: ‘id,name,email’}, function(response) {
What is the need of the function checkLoginState(). It hasn’t be used anywhere in the script.
Please reply soon.
why am i getting FB is not defined error in mozilla? It is working fine in chrome
Please update the subscriber list. I need the script.
why m not been able to download??? i subscribed and waiting for almost 1 days.
Hello plz update a subscribers list
I wait more than 20 hour
Hi dude,
i use script you it’s ok but …
Email : undefined
First Name : undefined
Last Name : undefined
in demo it show all data that work but i download and use it not show same demo.
how i can fix it ?
Thank you dude 😀
Hey,
Can you please send the script. I have subscribed but not be able to download it.
Please send it at: ans.raghav.100@gmail.com
what values store in $name,$email,$id variable ? Could you tell me.. and how to declare those variable with Facebook Name, Email, and ID. thanks.
That’s fine. I found the solutions.
Hey,
Can you please send the script. I have subscribed but not be able to download it.
Please send it at: ans.raghav100@gmail.com
hi,
please download now
thanks
Can’t download it. i have waited 24 hours already….after subscribed !
Hi Chanthea,
Sorry for the Inconvenience caused…
I have updated the database now.. Please download it from here – http://demos.w3lessons.info/facebook-oauth2-login/
Thanks
why m not been able to download??? i subscribed and waiting for almost 2days.
Hi Deep,
Sorry for the Inconvenience caused…
Just now I have updated the database.. Please download the code from here – http://demos.w3lessons.info/facebook-oauth2-login/
Let me know If you need any help..
Thanks
Hi sir , i can`not download this script :
Email does not exist in our database. Please use below form to subscribe
. But i subscribe your feeds
Why the facebook data cannot insert into database d?
Sir your code has the risk of SQL Injection.
HI Brian,
Ya.. I know that.. I din’t used binding param in PDO.
This is the sample code only for learning purpose.
Thanks
Thanks for the response.
As a feedback would be great that you teach without security risk so people do not tend to make those kind of mistakes. Otherwise i know you have that knowledge, but that’s just my humble opinion. Keep on my friend.
Thanks.
“This is the sample code only for learning purpose.”
Yes, and your readers are learning to write code that is open to security injections. Also, extract( $_POST ) is incredibly dangerous and there is no sane reason to do so. The same people who might not understand SQL injections are also probably not going to understand the security implications of using extract.
Until these issues are fixed I have to recommend against using this tutorial. There are already so many poorly-written PHP tutorials online, I hate to see another one added to the list.
In demo you are only fetching public data right, since it did’nt ask me for any permission.
yes.. You are right 🙂