Adding Facebook Login with PHP

By | August 6, 2015

Facebook is what I call the largest nation in the world as almost everybody now has an account on facebook. Adding facebook login to your website provides your users with a fast, easy and secure way of loggin in and signing up.

Creating a Facebook login system is really easy to create and doesn’t take much time to implement in your web applications. You can have a look at the live demo to understand its working. The live demo will not work correctly, Facebook has banned me from creating apps. The live demo will be back in a few days.

To get started you will need to create Facebook application. Creating a Facebook application is easier than you think. Follow the below guide to get your first Facebook application up and running.

Creating A Facebook Application

To create an application open Facebook’s Developer Site in your browser. Now, take your mouse over the “My Apps” menu item and click “Add A New App” Link. Now, choose ‘Website’ as the platform. Fill the dialog box with an App Name and choose a Category then click the “Create App ID” button. Now, navigate to the “Settings” Tab and click the “Add Platform” Button. Then in the popup select “Website” as the platform. Now type in the URL of your website. You will also need to add the domain name of your website to the “App Domains” input field.

Facebook allows the use of ‘localhost’ as the URL when developing locally.

That’s it, You have successfully created your first Facebook APP. Remember to copy the ‘APP ID’ and ‘APP Secret’. We will need them later in this tutorial.

Now, you will need the PHP SDK to start integrating Facebook Login with your website. You can download the Facebook’s PHP SDK here.

Creating The Database And Table

To create the database and the table for our Facebook login system, run the below SQL query on your MySQL server.

 

In the above SQL query, I am first Creating a database named facebooklogindemo which we will use later in this tutorial. After that I am creating a new table named ‘users’.

As the name implies, the ‘users’ table will contain all our users. It contains a ‘user_id’ column which is the unique user id for all our users, is the primary key for the table, is not allowed to be null and is set to Auto Increment. It also contains some Basic fields like first name(f_name), email, gender, etc. It also contains an access_token and a facebook_id field which we will use to store the Facebook User’s Access Token and User’s Numerical Facebook ID respectively.

Coding The Login System

To start coding the login system, You will first need the Facebook’s SDK for PHP. You can get it here.
After downloading the SDK, extract it into a directory named similar to ‘SDK’ or ‘FacebookSDK’.

For the login system you will need to create 3 files:
1. config.inc.php – This file will contain our MySQL database credentials. And also a function to check whether the user is logged in.
2. facebooklogin.php – This file will be responsible for registering the user in our database and logging the user in.
3. logout.php – This fill will be responsible for logging out the user from our website.

Let’s now code the files one by one.

config.inc.php

The complete code for config.inc.php:

 

You will need to replace all the database credentials in this file with yours to make our login system work. If you don’t know your MySQL server’s host name then you can use ‘localhost’ instead.

facebooklogin.php

The Complete Code For facebooklogin.php file:

 

Let’s break the code into parts for better understanding:

Part 1:

In the above code snippet, We are first starting the session which is necessary for our Login System to work. After that we are including our config.inc.php file which contains our database credentials. And then we are including the Facebook SDK’s autoload.php file which will load all the PHP files for the SDK.

Part 2:

Now in this part, We are first creating a new connection to MySQL server with the help of the MySQLi class. We are storing the MySQLi reference in the variable $mysqli which will be used throughout the code of our login system.
After that we are Importing all of the Namespaces from Facebook SDK we will use in our Login System. These Namespaces contain functions and classes of the Facebook SDK.

Part 3:

In the above code snippet, We are first setting the default Facebook Application we want to use. You will need to change the credentials passed to the function with your Facebook app’s real credentials. These credentials can be found on the dashboard of your Facebook App.
After that we are setting up a Facebook Redirect Login Helper. This will basically help us redirect the user to Facebook in order to login to our Facebook APP. In the constructor we are passing an absolute URL to our facebooklogin.php file. User will be redirected to this URL after logging in. Then we are storing this reference in the variable $redirect_login_helper.

Part 4:

Now in the above code snippet we are making a call to the getSessionFromRedirect function and storing its result in the $session variable. Facebook will throw a FacebookRequestException exception if there was any error. The getSessionFromRedirect function checks if Facebook has sent us any data after redirecting the user to login page. Facebook will only send us any data after redirecting the User to Facebook.

Part 5:

In this part, we are first checking if the $session variable is set. If the $session variable is set then it means that we have already redirected the user to Facebook. And if not then it means that we haven’t yet redirected the user.
In the else block, We are first creating a new array with the parameters to be passed to the getLoginUrl function. The array contains a key named scope which defines the scope of our Facebook Application and a key named redirect_uri which defines the URL to redirect the user to after logging in.
The scope defines what information about the user our Application can access. The ‘public_profile’ and ’email’ are default and don’t require any review from Facebook. But if you need extended scope, You will have to submit your application for a review to Facebook. Have a look at the permissions page of the Facebook documentation for more information on scope of the application.
After that we are passing the $param array to the getLoginUrl function of the redirectLoginHelper. The getLoginUrl function returns a string with the URL where we need to redirect the User to for Logging in. After receiving the Login URL, You can either redirect the user directly to the Login URL or display a link or fancy button instead. For this tutorial, I am using a link.

Part 6:

The above code snippet is from the if( isset($session) ) statement. In the above code snippet we are creating a new Facebook Request with the help of the FacebookRequest Class which accepts 3 necessary parameters:
1. $session(required) – The current FacebookSession object we received from the Redirect.
2. $method(required) – The request method, It can be GET, POST, DELETE or PUT depending on the endpoint you are making a request to.
3. $path(required) – The path for the request. In our case it is ‘/me’ which denotes the current authenticated user.

After that, we are executing the Facebook Request with the $request object. And then we are using the response generated to get the Graph Object for the request. The Graph Object contains all the information we requested.
After that, we are storing all the necessary user information into variables named accordingly.

Part 7:

In this part, we are first checking if the current user with the facebook_id already exists in our database. And if the user doesn’t exist in the database then we are first escaping all the data we stored in the variables and then we are inserting the data into the database.
After that we are setting up the session variables for the user. Escaping the data received from the Facebook API might seem funny and unusual but in order to secure your PHP applications, you should never trust any data you get.

And if the user already exists then we are fetching the Row for the user and setting the session variables and redirecting him back to the index.php files.

Now, we have successfully created a Facebook Login system but we still need a function to check if the user is logged in.

Add the below code at the end of the config.inc.php file and include it on all the pages where you need to check whether the user is logged in or not.

The above PHP function is quite easy to understand. We are just checking if the user_id exists in the session variable and is numeric. If it is then the user is logged in and if not then the user isn’t logged in yet.

logout.php

The complete code for logout.php file:

In this file, we are first starting the session and then we are including the config.inc.php file which contains our is_user_logged_in function.
After that we are using the is_user_logged_in function to check if the user is logged in. And if the user is logged in then we are destroying the session which will log the user out of our website.

Conclusion

Facebook Login provides an alternate way to register on your website which not only improves user experience but also increases the number of user sign ups on your website. It also makes the registration process easier, secure and faster for the user.
There are times when you need to collect more information about the users then Facebook provides. In that case, you can’t rely on Facebook login. I only include Facebook Login functionality in projects that really need it.

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *