Please support us by disabling ad blocker for smarttutorials.net ...

Facebook OAuth 2 Login Using PHP

Posted by & filed under CSS, HTML5, JQUERY, MYSQL, PHP.

In this we are going to see how to implement Facebook OAuth 2 Login using PHP to our webapplications.

Note : I am using Facebook PHP SDK 4 it will require minimum PHP version 5.4, So upgrade your php version before continuing this tutorial.

Please refer my previous tutorial on user login and registration.

1. User registration, Login and Forget Password Using PHP5, MySQLi, jQuery and Bootstrap

2. Sign in with Twitter OAuth API Using PHP

3. Login with Google OAuth 2 Using PHP and MySQL

 

 

 Facebook OAuth 2.0 login Using PHP

Facebook OAuth 2.0 login Using PHP

Step 1:

 

 

Create your Facebook account , If you don’t have already  please create your Facebook account by going through following URL

https://www.facebook.com/

To integrate Facebook OAuth 2 Authentication to your web-applications you must have Facebook application, So please create your Facebook Application by going through following URL.

https://developers.facebook.com/

Now Login into Facebook developer account using your Facebook login details.

Step 2:

Create new app by click on it like in the below picture.

Facebook OAuth 2 Login using PHP

Facebook OAuth 2 Login using PHP

Now choose website.

Facebook OAuth 2 Login using PHP

Facebook OAuth 2 Login using PHP

Now enter your app name.

Facebook OAuth 2 Login using PHP

Facebook OAuth 2 Login using PHP

Then choose app category and click on create App ID button to create your Facebook app now. Now you successfully created your Facebook Application. Now click on app that you have just created, it will go to the application dashboard.

Facebook OAuth 2 Login using PHP

Facebook OAuth 2 Login using PHP

Now click show button on the app secret to get app secret. Please note it down both App ID and App Secret details, as well fill the all details like in the above picture.

Finally enable this app to available to the public use, while enabling it will ask you to provide email, if you are not provided on the settings tab.

Facebook OAuth 2 Login using PHP

Facebook OAuth 2 Login using PHP

Now your Facebook App creation related task is completed.

Step 3:

Please Download Facebook PHP SDK from the Facebook site.

https://developers.facebook.com/docs/php/gettingstarted/4.0.0

Step 4:

Now create config.php file and define app related constants. Replace your Facebook APP ID, APP SECRET and Callback URL.

<?php
/**
@author muni
@copyright http:www.smarttutorials.net
 */

require_once 'messages.php';

//site specific configuration declartion
define( 'BASE_PATH', 'http://localhost/user_login/index.php');
define( 'DB_HOST', 'localhost' );
define( 'DB_USERNAME', 'root');
define( 'DB_PASSWORD', '');
define( 'DB_NAME', 'user_login');

//Facebook App Details
define('FB_APP_ID', 'YOUR APP ID');
define('FB_APP_SECRET', 'YOUR APP SECRET');
define('FB_REDIRECT_URI', 'http://localhost/user_login/');

function __autoload($class)
{
	$parts = explode('_', $class);
	$path = implode(DIRECTORY_SEPARATOR,$parts);
	require_once $path . '.php';
}

Step 5:

Now create index.php file and add the php below script. It make API request to the Facebook OAuth API while user clicks on Signin with Facebook button, as well it handles the response Facebook provides.

<?php 
ob_start();
session_start();
require_once 'config.php'; 

//initalize user class
$user_obj = new Cl_User();

/*********Facebook Login **********/
require_once('Facebook/FacebookSession.php');
require_once('Facebook/FacebookRedirectLoginHelper.php');
require_once('Facebook/FacebookRequest.php');
require_once('Facebook/FacebookResponse.php');
require_once('Facebook/FacebookSDKException.php');
require_once('Facebook/FacebookRequestException.php');
require_once('Facebook/FacebookAuthorizationException.php');
require_once('Facebook/GraphObject.php');
require_once('Facebook/GraphUser.php');
require_once('Facebook/GraphSessionInfo.php');
require_once( 'Facebook/HttpClients/FacebookHttpable.php' );
require_once( 'Facebook/HttpClients/FacebookCurl.php' );
require_once( 'Facebook/HttpClients/FacebookCurlHttpClient.php' );
require_once( 'Facebook/Entities/AccessToken.php' );
require_once( 'Facebook/Entities/SignedRequest.php' );

use Facebook\FacebookSession;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookRequest;
use Facebook\FacebookResponse;
use Facebook\FacebookSDKException;
use Facebook\FacebookRequestException;
use Facebook\FacebookAuthorizationException;
use Facebook\GraphObject;
use Facebook\GraphUser;
use Facebook\GraphSessionInfo;

 FacebookSession::setDefaultApplication(FB_APP_ID, FB_APP_SECRET);

$helper = new FacebookRedirectLoginHelper(FB_REDIRECT_URI);
$session = $helper->getSessionFromRedirect();

if(isset($_SESSION['token'])){
	$session = new FacebookSession($_SESSION['token']);
	try{
		$session->validate(FB_APP_ID, FB_APP_SECRET);
	}catch(FacebookAuthorizationException $e){
		echo $e->getMessage();
	}
}

$data = array();

if(isset($session)){
	$_SESSION['token'] = $session->getToken();
	$request = new FacebookRequest($session, 'GET', '/me');
	$response = $request->execute();
	$graph = $response->getGraphObject(GraphUser::className());

	$data = $graph->asArray();
	$id = $graph->getId();
	$image = "https://graph.facebook.com/".$id."/picture?width=100";
	$data['image'] = $image;
	$user_obj->fb_login($data);
} 
/*********Facebook Login **********/

?>
<?php 
	if( !empty( $_POST )){
		try {

			$data = $user_obj->login( $_POST );
			if(isset($_SESSION['logged_in']) && $_SESSION['logged_in']){
				header('Location: home.php');
			}
		} catch (Exception $e) {
			$error = $e->getMessage();
		}
	}
	//print_r($_SESSION);
	if(isset($_SESSION['logged_in']) && $_SESSION['logged_in']){
		header('Location: home.php');
	}
?>
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Smart Login Page</title>
	<link href='http://fonts.googleapis.com/css?family=Pacifico' rel='stylesheet' type='text/css'>
    <!-- Bootstrap -->
    <link href="css/bootstrap.min.css" rel="stylesheet">
    <link href="css/font-awesome.min.css" rel="stylesheet">
    <link href="css/login.css" rel="stylesheet">
    <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
    <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
    <script src="js/jquery.min.js"></script>
    <!-- Include all compiled plugins (below), or include individual files as needed -->
    <script src="js/bootstrap.min.js"></script>
  </head>
  <body>
	<div class="container">
		<?php require_once 'templates/ads.php';?>
		<div class="login-form">
			<?php require_once 'templates/message.php';?>
			<h1 class="text-center">Smart Tutorials</h1>
			<div class="form-header">
				<i class="fa fa-user"></i>
			</div>
			<form id="login-form" method="post" class="form-signin" role="form" action="<?php echo $_SERVER['PHP_SELF']; ?>">
				<input name="email" id="email" type="email" class="form-control" placeholder="Email address" autofocus> 
				<input name="password" id="password" type="password" class="form-control" placeholder="Password"> 
				<button class="btn btn-block bt-login" type="submit">Sign in</button>

				<h4 class="text-center login-txt-center">Alternatively, you can log in using:</h4>

				<a class="btn btn-default facebook" href="<?php echo $helper->getLoginUrl(array('email'));?>"> <i class="fa fa-facebook modal-icons"></i> Sign In with Facebook </a>  
				</form>
			<div class="form-footer">
				<div class="row">
					<div class="col-xs-6 col-sm-6 col-md-6">
						<i class="fa fa-lock"></i>
						<a href="forget_password.php"> Forgot password? </a>

					</div>

					<div class="col-xs-6 col-sm-6 col-md-6">
						<i class="fa fa-check"></i>
						<a href="register.php"> Sign Up </a>
					</div>
				</div>
			</div>
		</div>
	</div>
	<!-- /container -->
    <script src="js/jquery.validate.min.js"></script>
    <script src="js/login.js"></script>
  </body>
</html>
<?php ob_end_flush(); ?>

Step 6:

Find User.php file. It has fb_login method, that saves Facebook OAuth response in Database and signin user to your application.

/**
	 * This method will handle Facebook login
	 * @param array $data
	 * @throws Exception
	 * @return boolean true or false based on success or failure
	 */

	public function fb_login( array $data )
	{
		if( !empty( $data ) ){
			// Trim all the incoming data:
			$trimmed_data = array_map('trim', $data);
		}	

		// escape variables for security
		$name = mysqli_real_escape_string( $this->_con, $trimmed_data['name'] );
		$email = mysqli_real_escape_string( $this->_con, $trimmed_data['email'] );
		$social_id = mysqli_real_escape_string( $this->_con, $trimmed_data['id'] );

		$query = "SELECT user_id, name, email, created FROM users where email = '$email' and social_id = '$social_id' ";
		$result = mysqli_query($this->_con, $query);
		$data = mysqli_fetch_assoc($result);
		$count = mysqli_num_rows($result);
		if( $count == 1){
			$_SESSION = $data;
			$_SESSION['logged_in'] = true;
			return true;
		}else{

			$query = "INSERT INTO users (user_id, name, email, social_id, created) VALUES (NULL, '$name', '$email', '$social_id', CURRENT_TIMESTAMP)";
			if(mysqli_query($this->_con, $query));
			$query = "SELECT user_id, name, email, created FROM users where email = '$email' and social_id = '$social_id' ";
			$result = mysqli_query($this->_con, $query);
			$data = mysqli_fetch_assoc($result);
			$count = mysqli_num_rows($result);
			if( $count == 1){
				$_SESSION = $data;
				$_SESSION['logged_in'] = true;
				return true;
			}else{
				throw new Exception( LOGIN_FAIL );
			}
		}

	}

 .

Download Premium Only Scripts & 80+ Demo scripts Instantly at just 1.95 USD per month + 10% discount to all Exclusive Scripts

If you want any of my script need to be customized according to your business requirement,

Please feel free to contact me [at] muni[at]smarttutorials.net

Note: But it will be charged based on your customization requirement

Get Updates, Scripts & Other Useful Resources to your Email

Join 10,000+ Happy Subscribers on feedburner. Click to Subscribe (We don't send spam)
Every Email Subsciber could have access to download 100+ demo scripts & all future scripts.

  • AnujGupta19

    When i hit cancel during the authorization ,it doesn’t redirect me to the index.php page. What should i do ?

  • Arjit

    Fatal error: Uncaught exception ‘Exception’ with message ‘Email and Password are mismatch’ in C:xampphtdocsuser_loginClUser.php:143 Stack trace: #0 …user_loginindex.php(64): Cl_User->fb_login(Array) #1 {main} thrown in …user_loginClUser.php on line 143

    getting the above error can u please check and let me know

  • Hendra Wijaya

    yes. me too. please author, reply us.

  • Rahul Dahake
  • Thank You Rahul…

  • Its not working. I downloaded the latest (facebook-php-sdk-v4-4.0-dev) from facebook. And replaced the “Facebook” folder.
    The problem is, when it asks “yourapp will receive the following info: your public profile and email address” . And i press okay. It is showing a blank page, it is not redirecting, Please help

  • Gagandeep Sharma

    Hi muni,

    While using FB login tutorial. After pressing Ok on consent screen then i am not getting redirected

    Exception says

    [23-Jul-2015 11:25:05 Etc/GMT] PHP Fatal error: Uncaught exception ‘FacebookFacebookAuthorizationException’ with message ‘Missing redirect_uri parameter.’ in /home/parikla3/public_html/shop/Pari/social_login/Facebook/FacebookRequestException.php:134
    Stack trace:
    #0 /home/parikla3/public_html/shop/Pari/social_login/Facebook/FacebookRequest.php(268): FacebookFacebookRequestException::create(‘{“error”:{“mess…’, Object(stdClass), 400)
    #1 /home/parikla3/public_html/shop/Pari/social_login/Facebook/FacebookRedirectLoginHelper.php(175): FacebookFacebookRequest->execute()
    #2 /home/parikla3/public_html/shop/Pari/social_login/login.php(57): FacebookFacebookRedirectLoginHelper->getSessionFromRedirect()

  • Gagandeep Sharma

    Hi Muni…

    This is solved by upgrading PHP version to 5.6. Earlier i was having 5.4

    but now issue is that EMail and Image is not getting saved in database.

  • Oh Great.. Now print the insert query and check..

  • Gagandeep Sharma

    Muni.. when i try to print getEmail() likewie getId() function then get email is returning null..

  • Gagandeep Sharma

    Muni.. when i am priting google response then it is as below:

    Array
    (
    [user_ids] => 9
    [names] => Gagandeep Sharma
    [emails] =>
    [createds] => 2015-07-24 08:11:54
    [logged_ins] => 1
    )

    email is null man 🙁

  • Hi,

    Sorry for the delay..

    Did you got the answer?

    You need request email while oauth request … recently facebook changed that..

  • Gagandeep Sharma

    where do i need to change that????

  • Prashanth

    instead of
    $facebook->api(‘/me’);

    Use
    $facebook->api(‘/me?fields=id,first_name,last_name,email,gender,locale’);

  • Gagandeep Sharma

    but it is not working either man’

  • Deepak verma

    hi sir ,

    i am using FB Login tutorial ,i am getting below exception when pressing Ok on consent screen.

    1> Notice: Undefined index: email in C:wampwwwuser_login_fbClUser.php on line 118

    2>Fatal error: Uncaught exception ‘Exception’ with message ‘Email and
    Password are mismatch’ in C:wampwwwuser_login_fbClUser.php on line 156

    3> Exception: Email and Password are mismatch in C:wampwwwuser_login_fbClUser.php on line 156

    please help me sir i am new in php

    thank you in advance

  • Sandip Shitole

    thanks for tutorial ,it’s working fine for me ,but the issue is i m nt getting user email,plz help,thanks in advance…!

  • Shivani Sehdev

    Thank You Very Much Sir , Helped me a lot , I was Just looking form something like this from months……..
    Thanks a TON……..

  • Shivani Sehdev

    Hey Deepak did You get the solution to this problem as m also getting same error

  • Shivani Sehdev

    I Just Got the Solution in the INSERT QUERY table name was given user insted of (users)

    . Means just a simple and important ‘s’ was missing , making it clear solves the problem

  • Hi,

    Fixed that issue , will post updated tutorial shortly.

  • Shivani Sehdev

    Hey Thanks Muni , As You Can See Anyhow I Just Solved That Issue . But When I Tried To Integrate your Google login And Facebook login together It is Giving complications . Separately Both Are Working Fine.

  • Shivani Sehdev

    Hey Thanks Muni , As You Can Anyhow I Just Solved That Issue . But When I Tried To Integrate your Google login And Facebook login together It is Giving complications . Separately Both Are Working Fine.
    If You Say I Will Share My Source Code With You .
    .

  • Hi muni, thanks for tutorial. I could not get an email from the user. Can you help me, where is the problem?

  • shilpa

    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.

  • Your redirect URL given in the config.php file & website URL given in the Facebook must match… please check

  • Sathiya Seelan

    hi muni,
    how to post on facebook in offline

  • Slim Fillmore

    Did not work here! After login got this URL:

    MYDOMAIN.COM/login/?code=AQBqGTI8UEz5aK5hytl6qhPB-nkRfliJJF0-4u_LiSXtNuhjHs7ss8M5YVoavyMnLpL_pxsCeRsqCNDhCAQMeNz6Lj6xttcYfv0Px-XAlEKUTkezcYzEY7GvNsqENwGnhguKR2S4Gitm8-Kjb8Ly3XR6AwcYj6TD292L38AqE46Q2v2kyMNQgv5YCxz2byafMQ2Hb-mUoaESRfCHi-7wiOxECttJlxPDOv5Qbf-iJz_nLvq0bdwzKLJNexVgYuaiEkrWUIhX7Ndh6c-cnWurTHUZdopFfHtHTaDcW95_xBotPgPwBg9ycXJIY0PiEvkEU-I&state=4fa0d6fb5640f3bf9bc830e7705aff2d#_=_

    And is not logged.

  • vipin gupta

    hi im getting errors given below….

    Parse error: syntax error, unexpected T_STRING, expecting T_CONSTANT_ENCAPSED_STRING or ‘(‘ in C:inetpubvhostslocoturf.comhttpdocssociallogin.php on line 38

    Please help me..

  • check for syntax error…

  • Kapil Saini

    Error after click on login with facebook…

    Fatal error: Uncaught exception ‘FacebookFacebookSDKException’ with message ‘couldn’t connect to host’ in /home/u207436523/public_html/fb/Facebook/HttpClients/FacebookCurlHttpClient.php:156 Stack trace: #0 /home/u207436523/public_html/fb/Facebook/FacebookRequest.php(248): FacebookHttpClientsFacebookCurlHttpClient->send(‘https://graph.f…’, ‘GET’, Array) #1 /home/u207436523/public_html/fb/Facebook/FacebookRedirectLoginHelper.php(175): FacebookFacebookRequest->execute() #2 /home/u207436523/public_html/fb/index.php(41): FacebookFacebookRedirectLoginHelper->getSessionFromRedirect() #3 {main} thrown in /home/u207436523/public_html/fb/Facebook/HttpClients/FacebookCurlHttpClient.php on line 156

  • AMIT SAMOTA

    it is because of the version of php . Use php 5.4 and above

  • AMIT SAMOTA

    in ur config.php // define(‘FB_REDIRECT_URI’, ‘Same as on redirect url in facebook app’);

    ur redirect url should be same on fb app and config.php

  • AMIT SAMOTA

    in your index.php line 56 replace it with this one:
    $request = new FacebookRequest($session, ‘GET’, ‘/me?fields=id,name,email,gender,locale’);

  • AMIT SAMOTA

    in your index.php line 56 replace it with :

    $request = new FacebookRequest($session, ‘GET’, ‘/me?fields=id,name,email,gender,locale’);

  • AMIT SAMOTA

    in file user.php
    ‘INSERT QUERY user ‘ replace user with users

  • bhakti

    redirect to same page(index.php) after login

  • Fatal error: Uncaught exception ‘Exception’ with message ‘Email and Password are mismatch’ in /home/itsoftwarepoint/public_html/demoproject/user_login_fb/Cl/User.php:156 Stack trace: #0 /home/itsoftwarepoint/public_html/demoproject/user_login_fb/index.php(64): Cl_User->fb_login(Array) #1 {main} thrown in /home/itsoftwarepoint/public_html/demoproject/user_login_fb/Cl/User.php on line 156

    getting the above error can u please check and let me know

  • Haz Hayder
  • aidenkers

    In file “FacebookRedirectLoginHelper.php” replace

    if (isset($response[‘access_token’])) {
    return new FacebookSession($response[‘access_token’]);

    by
    if (isset($response->access_token)) {
    return new FacebookSession($response->access_token);

  • Sandip Kc

    Posted 4:26 pm. I can get the date of how old this post so that I would avoid any posts that are more than 6 months old for facebook tutorials as they keep on changing api.

Get Instant Script Download Access!