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.

Get Instant Script Download Access!