We have seen a feature Login with Facebook on many online websites. Users don’t need to create an account on the website or remember the credentials. By using this login with Facebook feature, they can easily log in to any website.
It will make easy to users for access the website without filling long registration form and activate the account. That is quick process, you just click on Login with Facebook button and authenticate the process, how easy is it.
We have seen many tutorials on this topic but found they are not updated as per Facebook graph php version Or many are not working properly. In this tutorial, we are going to explain step by step process how to create login with Facebook using PHP SDK v5.
Steps to Create Login with Facebook Using PHP
Step 1: Create a Facebook App:
First, you have to create a Facebook app via developer account, for this go to the https://developers.facebook.com/apps/ link and click on the ‘Add a New App’ button.
A pop-up window appears, input the app display name and contact email id. After submitting this form your APP is created and a Dashboard will open.
Step 2: Do APP Settings:
Now click on Settings -> Basic option, here you will find APP ID and App Secret. Keep note this info, later we need to configure in Facebook Graph PHP SDK.
Enter App Domains value in this basic setting page and choose the relevant category as per your app requirement.
Note: As per the new Facebook update, to run the app in the live environment, you have to specify the Privacy Policy URL and App Deleted Instruction URL.
Now click on the ‘+ APP Platform’ option, it’s showing just below the same Basic setting page. On click, a pop up will appear. You have to choose which platform you are using for this Facebook Login App.
For making the login with Facebook website app, Click on the Website option, then add a login page web URL in it. Save the settings.
After doing this, have to add valid OAuth Redirect Url in Facebook Login -> Settings page. There is section Client OAuth settings. Put valid redirect URL here of your website. This url belongs to where the user will go after successful login via Facebook. Below we will explain about Redirect Url ‘callback.php’ script file.
Note: Facebook made changes in app authorization process. Now you can access the app via HTTPS domain only. Make sure you add a secure website link in App Settings.
By default, your created App is in development mode. To make it live you have to insert company’s Private Policy and Term of service URL in app setting page. These web URL are required to make it LIVE.
Click on App Review option in the left menu. Here you find the Make WebLogin app public option. Click on the button to make it public. Now Facebook developer app setting part is done.
Step 3: Download the Facebook PHP SDK v5
In next step download the Facebook PHP SDK kit from GitHub. The current version is 5.7.0, make sure you download the latest version.
This Facebook Graph SDK requires two things:
- PHP version should be 5.4 or greater.
- Have php_mbstring extension enabled.
To access this library, you have to install a composer on your server. Go to this download composer link and follow the installation instruction, it’s quite easy.
We only need ‘src’ folder files to implement login with Facebook feature.
Upload the ‘src’ folder files on your web server.
Step 4: Implement Script Files
Here is the File structure we need to create:
- index.php
- fblogin.php
- callback.php
First create an ‘index.php’ file to create a ‘Login with Facebook’ action button and pointed to ‘fblogin.php’ file. Check the below HTML form code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
<html> <head> <title>Login With Facebook</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> </head> <body> <div class="container" style="margin-top:20px;"> <h2 class="text-center" >Facebook Login Demo</h2> <div id="loginbox" style="margin-top:20px;" class="mainbox col-md-6 col-md-offset-3 col-sm-8 col-sm-offset-2"> <div class="panel panel-info" > <div align="center" style="padding-top:30px" class="panel-body" > <form id="loginform" class="form-horizontal" role="form"> <div style="margin-top:10px" class="form-group"> <div class="col-sm-12 controls"> <a id="btn-fblogin" href="fblogin.php" class="btn btn-primary">Login with Facebook</a> </div> </div> </form> </div> </div> </div> </div> </body> </html> |
Now create ‘fblogin.php’ file to handle Facebook login requests. In this, we have included uploaded Facebook PHP SDK file.
Configure your App ID and Secret Key in this file, also mention the same Redirect URL which you added in Facebook Login valid OAuth Redirect URL setting.
fblogin.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<?php session_start(); require_once( 'Facebook/autoload.php' ); $fb = new Facebook\Facebook([ 'app_id' => 'Put APP ID Here', 'app_secret' => 'Put Secret Key Here', 'default_graph_version' => 'v2.5', ]); $helper = $fb->getRedirectLoginHelper(); $permissions = ['email']; // Optional permissions for more permission you need to send your application for review $loginUrl = $helper->getLoginUrl('https://www.codefixup.com/demo/facebook-login-page/callback.php', $permissions); header("location: ".$loginUrl); ?> |
Next we need ‘callback.php’ file to use as a Redirect URL. As above we have explained where you need to put this valid Redirect URL in App Settings.
After successful login with Facebook, the user will redirect to this Web URL and shows logged in user Facebook account Full Name, Email and ID, etc.
callback.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
<?php session_start(); <span class="crayon-k ">require_once</span> <span class="crayon-s">'insert_db.php'</span><span class="crayon-sy">;</span> require_once( 'Facebook/autoload.php' ); $fb = new Facebook\Facebook([ 'app_id' => 'Put App ID Here', 'app_secret' => 'Put Secret Key Here', 'default_graph_version' => 'v2.5', ]); $helper = $fb->getRedirectLoginHelper(); try { $accessToken = $helper->getAccessToken(); } 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; } try { // Get the Facebook\GraphNodes\GraphUser object for the current user. $response = $fb->get('/me?fields=id,name,email,first_name,last_name', $accessToken->getValue()); } catch(Facebook\Exceptions\FacebookResponseException $e) { // When Graph returns an error echo 'ERROR: Graph ' . $e->getMessage(); exit; } catch(Facebook\Exceptions\FacebookSDKException $e) { // When validation fails or other local issues echo 'ERROR: validation fails ' . $e->getMessage(); exit; } $me = $response->getGraphUser(); echo "Full Name: ".$me->getProperty('name')."<br>"; echo "Email: ".$me->getProperty('email')."<br>"; echo "Facebook ID: <a href='https://www.facebook.com/".$me->getProperty('id')."' target='_blank'>".$me->getProperty ('id')."</a>"; ?> |
In this file, we are using getGraphUser() function to get user Facebook account information. You can create any graph api calls in the same way.
Using Login with Facebook with MySQL:
You can integrate this login with Facebook functionality with your MySQL database. For this you need to create a database table, to store user contact information. Click below query to create a new table:
1 2 3 4 5 6 |
CREATE TABLE IF NOT EXISTS `registered_users` ( `id` int(11) NOT NULL AUTO_INCREMENT, `facebook_id` varchar(255) NOT NULL, `name` varchar(255) NOT NULL, `email` varchar(255) NOT NULL, PRIMARY KEY (`id`) |
As above, we are getting user profile information like name, email, and Facebook ID via getGraphUser() method. We are using this information to check user data in database table.
Now create MySQL connection.php file with database access.
connection.php
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<?php $servername = 'localhost'; $username = 'USERNAME'; $password = 'PASSWORD'; $db = 'DATABASE NAME'; $conn = mysqli_connect($servername,$username,$password,$db) ; if (!$conn) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } ?> |
To check the user Facebook account exists in website database, we need to create an insert_db.php file, where we check is user already created Facebook login account in our database or not.
If user facebook ID is found in our database table then we update the user information otherwise insert new entry in table.
insert_db.php file
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<?php require 'connection.php'; function checkuser($conn, $facebook_id, $username, $email) { $sql1 = "select * from registered_users where facebook_id='$facebook_id'"; $check = mysqli_query($conn,$sql1); $checkdta = mysqli_num_rows($check); if (empty($checkdta)) { // New user Insertion $query = "INSERT INTO registered_users (facebook_id,name,email) VALUES ('$facebook_id','$username','$email')"; mysqli_query($conn,$query); mysqli_error($query); } else { // Returned user data update $queryupdate = "UPDATE registered_users SET name='$username', email='$email' where facebook_id='$facebook_id'"; mysqli_query($conn,$queryupdate); mysqli_error($query); } } ?> |
As you see, we have created a function checkuser() in the above script to validate user data in the database.
Now you just need to add the below code line in callback.php file after getGraphUser() method, where we are getting user profile information, name, email, and facebook Id.
1 2 3 4 5 6 7 8 |
$_SESSION['fb_id'] = $me->getProperty('id'); $_SESSION['user_name'] = $me->getProperty('name'); $_SESSION['email'] = $me->getProperty('email'); checkuser($conn, $_SESSION['fb_id'], $_SESSION['user_name'], $_SESSION['email']); /* ---- Redirection location after session ----*/ header("Location: index.php"); |
Conclusion
So, put this Login with Facebook feature on your website or app and make it more interactive. Hope this tutorial will help you to implement Login with Facebook using PHP SDK v5. If you are facing any issue to add this feature, leave a comment below. Thanks
View live demo and Free source code also available to Download.
Thanks your code is working
problem facebook login.there is a problem with the sql wrong message coming out.and the php This redirect failed because the redirect URI is not in the list of permissions in the application’s OAuth Client Settings. Make sure your OAuth client and internet connection is enabled, and add all application domains as a valid OAuth redirect URI.
please send a correct one because i paid for it
Please upload registered_users.sql file in your database and make sure same redirect url is used in Facebook app setting and fblogin.php file.