Login with Facebook using PHP


PHP Facebook login example; In this tutorial, we will learn how to make facebook login in PHP using SDK.

This tutorial has the purpose to share easy source code to create or implement a Facebook login app using PHP SDK. And we can download or use the complete source code of Facebook login using PHP.

How to Make Login with Facebook in PHP

Just follow the following easy steps to make login with Facebook in PHP:

  • Step 1 – Create a Facebook App
  • Step 2 – Install Facebook PHP SDK v5
  • Step 3 – Create index.php
  • Step 4 – Create profile.php

Step 1 – Create a Facebook App

First of all, we have to make an app in the Facebook Developer Console.

Because when we create an app in the Facebook Developer Console. Then Facebook provides some secret details. With the help of which we can integrate and implement Facebook login in node js app.

If we do not know how to make apps on Facebook Developer Console. So we can make an app in the Facebook Developer Console by following the steps given below:

Step 1 – Visit the following url https://developers.facebook.com/apps/ and create a new facebook app.

Step 2 – Create facebook app with email and app name look like below picture:

create facebook app with laravel

Step 3 – Then, Navigate to setting->advanced and add redirect URL, looks like below picture:

get credential with facebook

Step 4 – Now, add valid auth redirect url. So, click facebook login->setting and add valid auth redirect URL, looks like below picture:

laravel facebook

Step 5 – Finally, Navigate to facebook developers dashboard and copy the following App ID and App SECRET, looks like below picture:

facebook app id and app secret

Now, save facebook secret id and secret key,Which is found from the Facebook Developer Console App.

Step 2 – Install Facebook PHP SDK v5

Install facebook PHP SDK v5. So, Open the command prompt and then go to project root directory and execute the below-given command to install facebook PHP sdk v5:

 
 // project root directory

 cd/project_root_directory

 composer require facebook/graph-sdk

Step 3 – Create index.php

Create an index.php file, so visit app root directory and create it. This file code will show the facebook login.

So update the below code into index.php file

<?php
//initialize facebook sdk
require 'vendor/autoload.php';
session_start();
$fb = new Facebook\Facebook([
'app_id' => 'fb_key_id',
'app_secret' => 'fb_secret_id',
'default_graph_version' => 'v2.5',
]);
$helper = $fb->getRedirectLoginHelper();
$permissions = ['email']; // optional
try {
if (isset($_SESSION['facebook_access_token'])) {
$accessToken = $_SESSION['facebook_access_token'];
} else {
$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;
}
if (isset($accessToken)) {
if (isset($_SESSION['facebook_access_token'])) {
$fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
} else {
// getting short-lived access token
$_SESSION['facebook_access_token'] = (string) $accessToken;
// OAuth 2.0 client handler
$oAuth2Client = $fb->getOAuth2Client();
// Exchanges a short-lived access token for a long-lived one
$longLivedAccessToken = $oAuth2Client->getLongLivedAccessToken($_SESSION['facebook_access_token']);
$_SESSION['facebook_access_token'] = (string) $longLivedAccessToken;
// setting default access token to be used in script
$fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
}
// redirect the user to the profile page if it has "code" GET variable
if (isset($_GET['code'])) {
header('Location: profile.php');
}
// getting basic info about user
try {
$profile_request = $fb->get('/me?fields=name,first_name,last_name,email');
$requestPicture = $fb->get('/me/picture?redirect=false&height=200'); //getting user picture
$picture = $requestPicture->getGraphUser();
$profile = $profile_request->getGraphUser();
$fbid = $profile->getProperty('id');           // To Get Facebook ID
$fbfullname = $profile->getProperty('name');   // To Get Facebook full name
$fbemail = $profile->getProperty('email');    //  To Get Facebook email
$fbpic = "<img src='".$picture['url']."' class='img-rounded'/>";
# save the user nformation in session variable
$_SESSION['fb_id'] = $fbid.'</br>';
$_SESSION['fb_name'] = $fbfullname.'</br>';
$_SESSION['fb_email'] = $fbemail.'</br>';
$_SESSION['fb_pic'] = $fbpic.'</br>';
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
session_destroy();
// redirecting user back to app login page
header("Location: ./");
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
} else {
// replace  website URL same as added in the developers.Facebook.com/apps e.g. if we used http instead of https and used            
$loginUrl = $helper->getLoginUrl('https://tutsmake.com/Demos/php-facebook', $permissions);
echo '<a href="' . $loginUrl . '">Log in with Facebook!</a>';
}
?>

Step 4 – Create profile.php

Create a profile.php file, so visit app root directory and create it. This file code will show logged-in user information like name, email, avatar, etc.

So update the below code into profile.php file:

<?php
session_start();
?>
<head>
<title>Login with Facebook in PHP</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
</head>
<body>     
<?php if($_SESSION['fb_id']) {?>
<div class = "container">
<div class = "jumbotron">
<h1>Hello <?php echo $_SESSION['fb_name']; ?></h1>
<p>Welcome to Tutsmake.com</p>
</div>
<ul class = "nav nav-list">
<h4>Image</h4>
<li><?php echo $_SESSION['fb_pic']?></li>
<h4>Facebook ID</h4>
<li><?php echo  $_SESSION['fb_id']; ?></li>
<h4>Facebook fullname</h4>
<li><?php echo $_SESSION['fb_name']; ?></li>
<h4>Facebook Email</h4>
<li><?php echo $_SESSION['fb_email']; ?></li>
</ul>
</div>
<?php } ?>
</body>
</html>

Recommended PHP Tutorials

Jaspreet Singh Ghuman

Jaspreet Singh Ghuman

Jassweb.com/

Passionate Professional Blogger, Freelancer, WordPress Enthusiast, Digital Marketer, Web Developer, Server Operator, Networking Expert. Empowering online presence with diverse skills.

jassweb logo

Jassweb always keeps its services up-to-date with the latest trends in the market, providing its customers all over the world with high-end and easily extensible internet, intranet, and extranet products.

Contact
San Vito Al Tagliamento 33078
Pordenone Italy
Item added to cart.
0 items - 0.00
Open chat
Scan the code
Hello 👋
Can we help you?