packetcode logo
Facebook Login using php sdk v4

Facebook Login using php sdk v4

4630 views 1 year ago Tutorials PHP

When we develop a service website or an app which involves user communication login becomes the basic requirement, apart from the conventional login, now the trend is social login and it makes the login simple convenient and secure. This tutorial covers a detailed explanation of how to implement facebook login.

Setup

To start with go to the facebook developers page then move to the menu link docs there look for the php sdk in the left hand menu click on the link ‘getting started with facebook sdk for php’ and download a copy of php sdk. Then we also need to register our app with the facebook. Go to the facebook developers page, in the top menu click the create a new app button, it immediately opens a dialog box. Fill the display name of the app and choose a category, and i would use communication… and namespace is not required… then it prompts a security check… fill the recapita and it creates your app… its then redirects you to the dashboard of your app where you can find the app id and app secret. make a note of these two which we would use in our php code. before closing the window go to settings in the left hand menu click on add platform then click website mention your website root url and use the same in app domain as well...ill use packetcode.com... save the changes. thats it we are set.Now come back to the workspace.

Code Breakdown

I created a folder fblogin in the localhost www/apps and i kept all the sdk files in the folder by name lib alias ‘library’ to keep it organised. also created a file named index.php in the app root folder. To begint the code,it can be broadly divided into 3 stages

  • Inclusion of library files
  • Using namespaces
  • Process

Tutorial Video
A very simple tutorial to explain how to implement facebook login for website using php sdk v4.0. It also shows how to get the name of the user and full code for free download.

Demo and Download

Have an hands on experience on the code here with the live demo. Also download a copy of the code and test it...and your feedback in the comments would be greatly appreciated.

Stage 1 : Libraries Inclusion

The below are the set of files to be included in the page i feel you can easily understand its functionality based on the name given to the file just dump all those library inclusion…. and be careful about the path as i have my files in the library and so i used the path as mentioned below, based on the location of your sdk files accordingly change the paths if required also take care about the upper and lower case letters used in the file naming.


	/* INCLUSION OF LIBRARY FILES */
	require_once( 'lib/Facebook/FacebookSession.php');
	require_once( 'lib/Facebook/FacebookRequest.php' );
	require_once( 'lib/Facebook/FacebookResponse.php' );
	require_once( 'lib/Facebook/FacebookSDKException.php' );
	require_once( 'lib/Facebook/FacebookRequestException.php' );
	require_once( 'lib/Facebook/FacebookRedirectLoginHelper.php');
	require_once( 'lib/Facebook/FacebookAuthorizationException.php' );
	require_once( 'lib/Facebook/GraphObject.php' );
	require_once( 'lib/Facebook/GraphUser.php' );
	require_once( 'lib/Facebook/GraphSessionInfo.php' );
	require_once( 'lib/Facebook/Entities/AccessToken.php');
	require_once( 'lib/Facebook/HttpClients/FacebookCurl.php' );
	require_once( 'lib/Facebook/HttpClients/FacebookHttpable.php');
	require_once( 'lib/Facebook/HttpClients/FacebookCurlHttpClient.php');
	

Stage 2 : Using Namespaces

Create the namespaces as follows.


	/* USE NAMESPACES */
	
	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;
	use Facebook\FacebookHttpable;
	use Facebook\FacebookCurlHttpClient;
	use Facebook\FacebookCurl;
	

Stage 3 : Process

Now the final process...this gonna be big one so lets m break it to four steps it goes like this

  • Start of php session
  • Create the variables
  • Initialization
  • Check for returned facebook session

Step 1 : Start of Php Session

Start of a php session For this we use start_session() function


	/* 1 Stat Session */
	 session_start();
	

Step 2 : Create the variables

Create the variables appid, appsecret and redirect url we would use the id and secret created in the developer's page. This unique id and secret makes the facebook server understand which app has to be triggered to process the request and this redirect url is to tell the facebook server where it has to written the control after the completion of authentication process. for time being lets keep this blank.


	//2.Use app id,secret and redirect url
	 $app_id = '';
	 $app_secret = '';
	 $redirect_url='';
	

Step 3: Initialize the application,create the helper object and get the fb session

First we initialize the application, for which we gonna use static class FacebookSession and call the method setDefaultApplication it accepts two parameters app id and app secret it basically puts the key values into the session in background. then we need to create helper object for which we would use the new operator with the class FacebookRedirectLoginHelper and it accepts one parameter that is redirect url.


	//3.Initialize application, create helper object and get fb sess
	 FacebookSession::setDefaultApplication($app_id,$app_secret);
	 $helper = new FacebookRedirectLoginHelper($redirect_url);
	 $sess = $helper->getSessionFromRedirect();
	 

Once we have the helper object we can use the function getSessionFromRedirect to get the facebook session that has returned from the fb server after processing if at all if it happened. if the page is opened for the first time by the customer this would be a null value but if the page opens after the authentication then certainly a session values would exists

Step 4 : Check for returned facebook session

Here we check for returned facebook session. if the session exists we gonna extract the user information otherwise we would just echo out the login url


   //4. if fb sess exists echo name 
	 if(isset($sess)){
	 		//create request object,execute and capture response
		$request = new FacebookRequest($sess, 'GET', '/me');
		// from response get graph object
		$response = $request->execute();
		$graph = $response->getGraphObject(GraphUser::className());
		// use graph object methods to get user details
		$name= $graph->getName();
		echo "hi $name";
	}else{
		//else echo login
		echo '<a href='.$helper->getLoginUrl().'>Login with facebook</a>';
	}
	

Final steps

One last part is left.. we need to deploy this on to the server i have my domain packetcode.com let me use it the path for the files is packetcode.com/apps/fblogin this particular url where our application is running should be used in the redirect url...thats where facebook will return the control after processing the request.

its important to note that for your users to make use of this app you need to make the app public which can be done by submitting the app for review its very tedious process but worth doing it if you have noticed this is not complete login process we also need to implement logout… you can check that out here

im krishna Teja, im a computer science engineer by qualification, a physics teacher by profession and a programmer by interest. I'm an expert in building visually stunning web apps using javascript, ...