Login with Facebook and Google accounts in PHP

 

Every website maintain the users data on the database, for this one they using the signup.But now a days,instead of signup,they are using the social networks API’s. So,here we providing the Sign in with Google account using OAuth2.0 And Sign In with Facebook  using PHP SDK 3.0.

For this module,We need the Client ID,Client Secret and Registered Redirect Uri for Google and App Id and App Secret for Facebook .For Google one Please refer this article Create a Google OAuth2.0 Client ID. And  for the Facebook app creation please refer this article  Creation of the Facebook App


Live DemoLive Demo

Download Script

After getting the Google OAuth2.0 app details and facebook app details,define these app details in config.php file.

 <?php
session_start();
define('BASE_URL', filter_var('Your Domain Path', FILTER_SANITIZE_URL));
// Visit https://code.google.com/apis/console to generate your
// oauth2_client_id, oauth2_client_secret, and to register your oauth2_redirect_uri.
define('CLIENT_ID','OAUTH CLIENT ID');
define('CLIENT_SECRET','OAUTH CLIENT SECRET');
define('REDIRECT_URI','OAUTH REDIRECT URI');//example:http://localhost/social/login.php?google
define('APPROVAL_PROMPT','auto');
define('ACCESS_TYPE','offline');

//For facebook
define('APP_ID','Facebook App ID');
define('APP_SECRET','Facebook App Secret');
?>

In the config.php file,we defined the Access Type is offline.Basically Google OAuth2.0 provides two types of access which are offline and online. And also here we define Approval Prompt as ‘auto‘. In this script, the default value for the Approval Prompt is ‘force‘ and for the Access Type is ‘offline‘.

Here below shows the index.php file code.

<?php require_once 'config.php'; ?>
<!doctype html>
<html>
<head><meta charset="utf-8">
    <title>Signin with Social Accounts-Idiot Minds</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" src="js/oauthpopup.js"></script>
<script type="text/javascript">
$(document).ready(function(){
//For Gmail  
$('a.login').oauthpopup({
        path: 'login.php?google',
        width:650,
        height:350,
    });
    $('a.google_logout').googlelogout({
        redirect_url:'<?php echo BASE_URL; ?>logout.php?google'
    });
//For facebook
  $('#facebook').oauthpopup({
        path: 'login.php?facebook',
        width:600,
        height:300,
   });
});
</script>

</head>
<body>
 <div style="float:left;width:33%;margin-left:30%;">

<?php
 if(!isset($_SESSION['User'])) {    ?>
 <div  style="margin-left:10%;float:left;width:300px;">

       <img src='images/facebook.png' id='facebook'  style='cursor:pointer;float:left;margin-right:10%;'  alt="Sign in with Facebook"/>
<a class='login' href='javascript:void(0);'  style="float:left;"><img alt='Signin in with Google' src='images/google.png' /></a>
</div>

 <?php  } else { 
    if(isset($_SESSION['facebook_logout'])){  

     ?>
      <img src="https://graph.facebook.com/<?php echo $_SESSION['User']['id']; ?>/picture" width="50"/><div><?php echo $_SESSION['User']['name'];?></div>
      <a href="<?php echo $_SESSION['facebook_logout'];?>">Logout</a>
<?php }
    else{
  ?>
     <img src="<?php echo $_SESSION['User']['picture']; ?>" width="50" /><div><?php echo $_SESSION['User']['name'];?></div>
     <div><?php echo $_SESSION['User']['email']; ?></div>
       <a class='google_logout' href='javascript:void(0);'>Logout</a>
  <?php
    }
  } ?>
</div>

</body></html>

In this index.php file, we used the one oauthpopup jQuery plugin for Popup and Google logout. For logout,when click on this “Logout” link it will logout from the Google account after that it will redirect to specified url which is defined in index.php file like shown in below.

$(document).ready(function(){
//For Gmail
    $('a.login').oauthpopup({
        path: 'login.php?google',
        width:650,
        height:350,
    });
    $('a.google_logout').googlelogout({
        redirect_url:'<?php echo BASE_URL; ?>logout.php?google'
    });
//For Facebook
  $('#facebook').oauthpopup({
        path: 'login.php?facebook',
        width:600,
        height:300,
   });

});

Here below one is the login.php file .

require 'Social.php';
    $Social_obj= new Social();
if(isset($_GET['facebook'])){
    $Social_obj->facebook();
}
if(isset($_GET['google'])){
    $Social_obj->google();
}

?>
<!-- after authentication close the popup -->
<script type="text/javascript">
window.close();
</script>

In login.php file, we are using the Social.php class for authentication.In this file we pass the all the credentials for authentication which are defined in the Config.php file.

<?php
require_once 'config.php';
require_once 'lib/facebook/facebook.php';

require_once 'lib/google/Google_Client.php';
require_once 'lib/google/Google_Oauth2Service.php';

class Social{

 function facebook(){
     $facebook = new Facebook(array(
		'appId'		=>  APP_ID,
		'secret'	=> APP_SECRET,
		));
			//get the user facebook id		
			$user = $facebook->getUser();
			//echo $user;exit;
			if($user){
				try{
					//get the facebook user profile data
					$user_profile = $facebook->api('/me');
					$params = array('next' => BASE_URL.'logout.php');
					//logout url
					$logout =$facebook->getLogoutUrl($params);
					$_SESSION['User']=$user_profile;
					$_SESSION['facebook_logout']=$logout;
				}catch(FacebookApiException $e){
					error_log($e);
					$user = NULL;
				}		
			}
			if(empty($user)){
			  //login url	
			  $loginurl = $facebook->getLoginUrl(array(
							'scope'	=> 'email,read_stream, publish_stream, user_birthday, user_location, user_work_history, user_hometown, user_photos',
							'redirect_uri'	=> BASE_URL.'login.php?facebook',
							'display'=>'popup'
							));
			  header('Location: '.$loginurl);
			}

  }
    function google(){

			$client = new Google_Client();
			$client->setApplicationName("Idiot Minds Google Login Functionallity");
			$client->setClientId(CLIENT_ID);
			$client->setClientSecret(CLIENT_SECRET);
			$client->setRedirectUri(REDIRECT_URI);
			$client->setApprovalPrompt(APPROVAL_PROMPT);
			$client->setAccessType(ACCESS_TYPE);
			$oauth2 = new Google_Oauth2Service($client);
			if (isset($_GET['code'])) {
			  $client->authenticate($_GET['code']);
			  $_SESSION['token'] = $client->getAccessToken();
			}
			if (isset($_SESSION['token'])) {
			 $client->setAccessToken($_SESSION['token']);
			}
			if (isset($_REQUEST['error'])) {
			 echo '<script type="text/javascript">window.close();</script>'; exit;
			}
			if ($client->getAccessToken()) {
			  $user = $oauth2->userinfo->get();
			  $_SESSION['User']=$user;
			  $_SESSION['token'] = $client->getAccessToken();

			} else {
			  $authUrl = $client->createAuthUrl();
			  header('Location: '.$authUrl);

			}
      }

}

?>

In the logout.php file,we unset the OAuth2 Access token and Revoke an OAuth2 access token and also for facebook we destroy the entire session .

<?php
require_once 'config.php';

if($_GET['google']){
    require_once 'lib/google/Google_Client.php';    
    $client = new Google_Client();

    unset($_SESSION['token']);
    $client->revokeToken();    
}

if(isset($_SESSION['User']) && !empty($_SESSION['User'])){
session_destroy();
}
header('Location: '.BASE_URL);
?>

 

153 Comments

  1. G ParthaSarathi

    Really this example is very helpful and wonderful. Thank You

  2. I love this tutorial. Really help me alot. Thanks

Leave a Reply