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

Login with Facebook OAuth Using PHP

Posted by & filed under FACEBOOK, MYSQL, PHP.

In this tutorial we are going to implement Login with Facebook OAuth Using PHP. I have implemented Facebook OAuth login with different version of PHP SDK. I have used latest latest Facebook PHP SDK 4 in this tutorial. Please continuing this tutorial, Please refer my previous tutorial on

1. Facebook OAuth 2 Login Using PHP

2. OAuth Login for Facebook Twitter and Google Plus Using PHP

 

Login with Facebook OAuth Using PHP

Step 1: Create Facebook Application for OAuth Login:
To implement Facebook OAuth login in our application we have to create Facebook Application first. I have explained Facebook Application creation process in my previous tutorial. Please refer the following tutorial from step-1 to step-3.

Facebook OAuth 2 Login Using PHP

Step : Install Facebook PHP SDK using Composer:
I am using composer to download Facebook PHP SDK. So please install composer in your machine before doing anything. To install Composer please refer following tutorial Composer Installation for CakePHP 3 step.

Install CakePHP 3 using Composer

I have created project called test in my localhost. Inside test project folder, Please create composer.json file and add the following lines.

{
  "require" : {
    "facebook/php-sdk-v4" : "~5.0"
  }
}

Now do the following things like in below image to download Facebook PHP SDK in your test project folder.

Facebook PHP SDK Installation Using Composer

First you need to change working directory by running following commands in the command line.

cd C:\xampp\htdcos\test

Next you need to run following command in the command line.

composer install

This will download Facebook PHP SDK in your test project folder in like this.

Facebook PHP SDK Installation Using Composer

Note : if your getting error like this composer is not recognized as an internal or external command then you are not installed composer in your machine. If you installed composer then getting same error, then you need to close your command line and need to open it again.

Now you have done all prerequisites step to start Facebook Login implementation.

 

Create MySQL Table for Facebook OAuth Login:

Please create MySQL table for Facebook OAuth Login using SQL queries.

--
-- Table structure for table `social_users`
--

CREATE TABLE IF NOT EXISTS `social_users` (
  `id` int(10) unsigned NOT NULL,
  `first_name` varchar(50) NOT NULL,
  `last_name` varchar(50) NOT NULL,
  `email` varchar(60) NOT NULL,
  `password` varchar(60) NOT NULL,
  `social_id` varchar(100) NOT NULL,
  `picture` varchar(250) NOT NULL,
  `created` datetime NOT NULL,
  `uuid` varchar(70) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;

--
-- Indexes for dumped tables
--

--
-- Indexes for table `social_users`
--
ALTER TABLE `social_users`
  ADD PRIMARY KEY (`id`), ADD UNIQUE KEY `email` (`email`), ADD KEY `login` (`password`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `social_users`
--
ALTER TABLE `social_users`
  MODIFY `id` int(10) unsigned NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=1;

Facebook Login PHP Script

Now create config.php file to keep site wide configurations in one place. Here is the my config.php file content.

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

require_once 'messages.php';

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


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


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

In the above script please replace YOUR-FACEBOOK-APP-ID & YOUR-FACEBOOK-APP-SECRET with your Facebook app id and secret.

Now create index.php file and include the config.php file, Facebook SDK autoload file and start your session using session_start().

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

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

/*********Facebook Login **********/
require_once __DIR__ . '/vendor/autoload.php';

Before making any request to Facebook OAuth API, we need to initialize Facebook class by supplying Facebook APP ID & APP SECRET.

$fb = new Facebook\Facebook([
		'app_id' => FB_APP_ID,
		'app_secret' => FB_APP_SECRET,
		'default_graph_version' => 'v2.3',
]);

Obtaining Facebook Login URL

Using Facebook\Helpers\FacebookRedirectLoginHelper class getLoginUrl() method we are getting Facebook Login URL. This Facebook Login URL takes the user to the Facebook authorization screen and upon approval, will redirect the user to the URL you specified in the redirect URL.

$helper = $fb->getRedirectLoginHelper();
....
$permissions = ['email', 'public_profile']; // optional
$loginUrl = $helper->getLoginUrl(FB_REDIRECT_URI, $permissions);

Obtaining Facebook OAuth Access Token

When user clicks on the Login with Facebook button, it takes the user to the Facebook authorization screen and upon approval, it will redirect user to the page you have specified. Where in the redirect page you can able to get Facebook OAuth Access Token.

$accessToken = $helper->getAccessToken();

Obtain Email, First_name, Last_name & Picture From Facebook:

Once you successfully got the access token, then you can make a call to get email,first_name, last_name,picture from Facebook. here is the script how i a making call to Facebook to get email,first_name, last_name,picture.

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

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

/*********Facebook Login **********/
require_once __DIR__ . '/vendor/autoload.php';

$fb = new Facebook\Facebook([
		'app_id' => FB_APP_ID,
		'app_secret' => FB_APP_SECRET,
		'default_graph_version' => 'v2.3',
]);
$helper = $fb->getRedirectLoginHelper();




try {
	$accessToken = $helper->getAccessToken();
} catch(Facebook\Exceptions\FacebookResponseException $e) {
	var_dump($helper->getError());
	// When Graph returns an error
	echo 'Graph returned an error: ' . $e->getMessage();
	exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
	var_dump($helper->getError());
	// When validation fails or other local issues
	echo 'Facebook SDK returned an error: ' . $e->getMessage();
	exit;
}

if (isset($accessToken)) {
	// Logged in!
	$_SESSION['facebook_access_token'] = (string) $accessToken;

	// Now you can redirect to another page and use the
	// access token from $_SESSION['facebook_access_token']


	$fb->setDefaultAccessToken( $accessToken );

	try {
		$response = $fb->get('/me?fields=email,first_name, last_name,picture.type(large)');
		$userNode = $response->getGraphUser();

		$data = $userNode->asArray();

		if(!empty($data)){
			$user_obj->fb_login($data);
		}else{
			throw new Exception("Facebook returns empty resonse, Please contact admin.");
		}





	} catch(Facebook\Exceptions\FacebookResponseException $e) {
		// When Graph returns an error
		echo 'Graph returned an error: ' . $e->getMessage();
		exit;
	} catch(Facebook\Exceptions\FacebookSDKException $e) {
		// When validation fails or other local issues
		echo 'Facebook SDK returned an error: ' . $e->getMessage();
		exit;
	}
}



$permissions = ['email', 'public_profile']; // optional
$loginUrl = $helper->getLoginUrl(FB_REDIRECT_URI, $permissions);

/*********Facebook Login **********/

?>

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!