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

OAuth Login for Facebook Twitter and Google Plus Using PHP

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

So far in this series of user registration and login we had seen simple user login and registration using php objected oriented programming.

User registration and Login Using PHP5, MySQLi, jQuery and Bootstrap

Then we have seen how to integrate twitter OAuth login using PHP

Sign in with Twitter OAuth API Using PHP

Then we have seen integration of Facebook OAuth 2 login using PHP.

Facebook OAuth 2 Login Using PHP

Finally we had seen integration Google Plus OAuth 2 login using PHP.

Login with Google OAuth 2 Using PHP and MySQL

So in this tutorial we are going to implement the Facebook, Twitter and Google OAuth logins in single tutorial. So before continuing this tutorial please refer above four tutorials.

 

 

Demo OAuth Login for Facebook Twitter and Google Plus Using PHP

Demo OAuth Login for Facebook Twitter and Google Plus Using PHP

I had kept this social login handling in a separate php file (login.php), where i included all php SDK of Facebook, Twitter and login. When user clicks on login with Facebook, Twitter or Google, then user will be redirected to this login.php file. This login.php will make login request to Facebook, Twitter or Google. Once user successfully authenticated, then OAuth response will be saved in database and let the user to login in our application.

 

 

Here is the login.php file script.

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

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

/*** Twitter****/
require_once('twitteroauth/twitteroauth.php');
/*** Twitter****/

/*******Google ******/
require_once 'Google/src/config.php';
require_once 'Google/src/Google_Client.php';
require_once 'Google/src/contrib/Google_PlusService.php';
require_once 'Google/src/contrib/Google_Oauth2Service.php';
/*******Google ******/

/*********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);

if(isset($_GET['type']) && $_GET['type'] == 'facebook' ){

	$fb_url = $helper->getLoginUrl(array('email'));
	header('Location: ' . $fb_url);
}

$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;
	if($user_obj->fb_login($data)){header('Location: home.php');}
	else{header('Location: index.php');}
}
/*********Facebook Login **********/

/*******Google ******/

$client = new Google_Client();
$client->setScopes(array('https://www.googleapis.com/auth/plus.login','https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/plus.me'));
$client->setApprovalPrompt('auto');

if(isset($_GET['type']) && $_GET['type'] == 'google' ){
	$authUrl = $client->createAuthUrl();
	header('Location: ' . $authUrl);
}
$plus       = new Google_PlusService($client);
$oauth2     = new Google_Oauth2Service($client);
//unset($_SESSION['access_token']);

if(isset($_GET['code'])) {
	$client->authenticate(); // Authenticate
	$_SESSION['access_token'] = $client->getAccessToken(); // get the access token here 
	header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
}

if(isset($_SESSION['access_token'])) {
	$client->setAccessToken($_SESSION['access_token']);
}

if ($client->getAccessToken()) {
	$_SESSION['access_token'] = $client->getAccessToken();
	$user         = $oauth2->userinfo->get();
	try {
		if($user_obj->google_login( $user ))header('Location: home.php');
		else header('Location: index.php');
	}catch (Exception $e) {
		$error = $e->getMessage();
	}
}
/*******Google ******/

/*** Twitter****/
if (TWITTER_CONSUMER_KEY === '' || TWITTER_CONSUMER_SECRET === '' || TWITTER_CONSUMER_KEY === 'TWITTER_CONSUMER_KEY_HERE' || TWITTER_CONSUMER_SECRET === 'CONSUMER_SECRET_HERE') {
	echo 'You need a consumer key and secret to test the sample code. Get one from <a href="https://dev.twitter.com/apps">dev.twitter.com/apps</a>';
	exit;
}

if(isset($_GET['type']) && $_GET['type'] == 'twitter' ){ 
	$connection = new TwitterOAuth(TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET);
	$request_token = $connection->getRequestToken(TWITTER_OAUTH_CALLBACK);
	$_SESSION['oauth_token'] = $token = $request_token['oauth_token'];
	$_SESSION['oauth_token_secret'] = $request_token['oauth_token_secret']; 
	//echo "<pre>";print_r($connection);echo "</pre>";
	//echo "<pre>";print_r($_SESSION);echo "</pre>";exit;
	switch ($connection->http_code) {
		case 200:
			$url = $connection->getAuthorizeURL($token); //echo $url;exit;
			header('Location: ' . $url);
			break;
		default:
			$error = 'Could not connect to Twitter. Refresh the page or try again later.';
	}
}else{
	if(( isset( $_SESSION['oauth_token'] ) ) ){
		$connection = new TwitterOAuth(TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET, $_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
		$access_token = $connection->getAccessToken($_REQUEST['oauth_verifier']);
		$_SESSION['access_token'] = $access_token;
		$content = $connection->get('account/verify_credentials');
		$data = array();
		if( !empty( $content->id )){
			$data['id'] = $content->id;
			$data['name'] = $content->name;
			$data['screen_name'] = $content->screen_name;
			$data['picture'] = $content->profile_image_url;
			try {
				if($user_obj->twitter_login($data))header('Location: index.php');
			}catch (Exception $e) {
				$error = $e->getMessage();
			}

		}else{
			session_unset();
			session_destroy();
			header('Location: index.php');
		}
	}
}
/*** Twitter****/

 .

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.

  • Matt

    Please Give Your 2 Minutes to Read,

    Facebook earns $7.87 billion dollors per year, We use Facebook for social networking and to connect with our friends. Thus facebook earn revenue because of us but facebook never shares revenue with any facebook user.

    Although we spend our time on facebook, facebook never pays us anything. Wehy should we use facebook further?

    There is new social networking site launched called Tsu, which pays revenue to users means to us. Tsu gives earning opprtunities to us by using social netwok.

    This is very helpful for bloggers too, because bloggers get paid for his/her content.

    Click here to Join Tsu and to Start Earning..!!

    Q- How Can You Earn?

    A- You have to use Tsu as you use facebook, twitter etc.. nothing more than that.. Tsu will give you advertising revenue generated from the ads shown to your friends. Ads are similar as appears on Facebook.

    Click here to Join Tsu and to Start Earning

    Thanks for being the part of people’s welfare by approving this comment. Your Approval will surely help most of your readers to earn money. Just Click here to Sign Up for Tsu and to Start Earning

    Tsu Sign up | Tsu Shortcode | Join Tsu | Tsu Invitation | Tsu

    Thanks for approving this comment, you are helping your readears to earn money. Thanks for your participation in social welfare.

  • AnujGupta19

    Don’t you need a database for Facebook oauth ?

  • Yes , we need db for Facebook Oauth..

  • AnujGupta19

    What redirect url have you used for your demo ?

  • devendra

    What redirect url have you used for your demo ?

  • User

    when i click login with facebook .. it is checking with google oauth validation – Fatal error: Uncaught exception ‘Google_AuthException’ with message ‘Error fetching OAuth2 access token, message: ‘invalid_grant” .. if i remove google code in login.php then it is working..

  • Hendra Wijaya

    its not working. when i click facebook login then redirect to index.php again.

  • Chappi Luke

    Great tutorial, Keep it up, check another awesome tutorial

    https://www.youtube.com/watch?v=KG68R3akQj4

  • Anubhav

    it is throwing me on the same page index.php after logiin…
    i have used http://localhost/user_login/index.php this path in facebook app id as well as config file…
    #not working

  • Anubhav

    Yes it is same in my case…

  • Л. Отгонбаяр

    It didn’t get email address to mysql database.

  • Л. Отгонбаяр

    or is this nulled? or full?

  • Yusuf

    Please where exactly did I put Facebook API ID and App Secret

  • Yusuf

    FacebookSession::setDefaultApplication(FB_APP_ID, FB_APP_SECRET);
    $helper = new FacebookRedirectLoginHelper(FB_REDIRECT_URI);

    //please explain the above line with sample/example, thank

  • Please change in config.php file….

  • Gagandeep Sharma

    $helper->getSessionFromRedirect(); is returning null in my case.Please let me know the problem. This was working earlier but not now,

  • Yusuf

    its not add user details into database, please help out

  • Srinath

    Redirect URL is http:///login.php or http:///login.php. Same you have to give in Google app creation time as well as FB app creation time

  • dhaval

    hi
    this works fine for me but have simple problem , when i click on fb button its redirect on login page with $_GET[‘code’] and using google code… so how to fix it

  • Alfonso Del Río

    Thx so much for this tutorial¡¡
    I have one question: when i make fb login, in “email” field on my db i don’t receive any email. Why could be this?

  • Sandy Web

    after login thru Facebook it is redirecting back to index page. DB is not getting updated

  • Ishan

    from where do i downloaded it ? :'( already subscribed but no email sent

  • amit bhalani

    Parse error: syntax error, unexpected T_STRING, expecting T_CONSTANT_ENCAPSED_STRING or ‘(‘ in G:wampwwwsocial_loginlogin.php on line 38

  • Idbm Technology

    login with google and facebook working by this url but login with twitter not working i am using
    http:///login.php
    can anyone tell whats the problem..?

  • Idbm Technology

    login with google and facebook working by this url but login with twitter not working i am using
    http:///login.php
    sir tell whats the problem..?

  • Hussein Al Sherbiny

    does any one know anything about this error ?
    require_once(OAuthException.php): failed to open stream

  • Su Darmanto

    I want to show profile picture in the account page. I wanna ask, why the social-picture string location that saved in mysql table isn’t appear using below code?
    But if using ‘name’, ’email’ even ‘date created’ can appears normal.

    Profile Picture
    <img src=" ” width=”100px”>

    Thanks

  • gromikov

    So far I tried Google and its working fine, but when it comes to facebook Im able to see the facebook prompt for access and after clicking on ok I get redirected to the login page again and nothing get stored in the database nor the user gets logged in.

    Does anyone knows whats going on or how can I fix this issue?

  • Laksmi Gada

    I have tried google and facebook, google is working fine but i am facing logout issue in facebook. when i logout from facebook and login again it is directly logging in as previous user. How to solve this plz help me.

  • Adewunmi Adeyemi Dada

    how do i add Instagram and paypal

  • Madhu Cxo

    Fatal error: Cannot use object of type stdClass as array in /home/smarttut/public_html/demo_tut/social_login/Facebook/FacebookRedirectLoginHelper.php on line 176

    first solve ur website problem.

  • kennedy sakala

    Fatal error: Cannot use object of type stdClass as array in
    /xxxx/third_party/Facebook/FacebookRedirectLoginHelper.php on line 191

    solve the problem:

    if ($response instanceof stdClass && isset($response->access_token)) {

    return new FacebookSession($response->access_token);

    }

    if (is_array($response) && isset($response[‘access_token’])) {

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

    }

Get Instant Script Download Access!