All TalkersCode Topics

Follow TalkersCode On Social Media

devloprr.com - A Social Media Network for developers Join Now ➔

Login With Facebook In PHP

Last Updated : Mar 11, 2024

Login With Facebook In PHP

In this article we will show you the solution of login with Facebook in PHP, to login with Facebook in php We need the Facebook SDK which is the set of software components.

After opening the page in the localhost we have to download the Facebook SDK.

We can done it either using composer or by the Facebook developer site. In this tutorial we used the developer site.

Now at first, we have to follow some steps.

  1. First visit https://developers.facebook.com/, log in with the developer account then go to my app page
  2. Create an app through it and click on build connected experiences.
  3. Enter the name of your app (ex- demo_login)
  4. Visit www then enter the local host URL as Site URL
  5. Download the Facebook SDK for PHP, which provides a native interface to the Graph API and Facebook Login
  6. Paste the Facebook folder within the same folder as the php files.

Step By Step Guide On Login With Facebook In PHP :-

Config.php

<?php
 // Include the autoloader provided in the SDK
require_once(__DIR__.'/Facebook/autoload.php');
define('APP_ID', 'ENTER_APP_ID');
define('APP_SECRET', 'ENTER_APP_SECRET');
define('API_VERSION', 'v2.5');
define('FB_BASE_URL', 'ENTER_URL');
define('BASE_URL', 'YOUR_WEBSITE_URL');
if(!session_id()){
    session_start();
}
// Call Facebook API
$fb = new Facebook\Facebook([
 'app_id' => APP_ID,
 'app_secret' => APP_SECRET,
 'default_graph_version' => API_VERSION,
]);
// Get redirect login helper
$fb_helper = $fb->getRedirectLoginHelper();
// Try to get access token
try {
    if(isset($_SESSION['facebook_access_token']))
  {$accessToken = $_SESSION['facebook_access_token'];}
 else
  {$accessToken = $fb_helper->getAccessToken();}
} catch(FacebookResponseException $e) {
     echo 'Facebook API Error: ' . $e->getMessage();
      exit;
} catch(FacebookSDKException $e) {
    echo 'Facebook SDK Error: ' . $e->getMessage();
      exit;
}
?>
  1. We write <?php to write php within it then close it with ?> tag
  2. To include the autoloader provided in the SDK using required_once() tag
  3. Define the APP ID, APP SECRET, API VERSION, FB BASE URL
  4. Also Define the BASE URL
  5. If-else statement created if Session_id() not returned the session id for the current session.
  6. Now calling the Facebook API by including the folder and the APP ID, APP SECRET, API VERSION, FB BASE URL defined above.
  7. By creating a variable $fb_helper with the getRedirectLoginHelper() to get redirect to the login helper.
  8. Create a try-and-catch statement to try to get an access token.

Index.php

<?php
require_once 'config.php';
$permissions = ['email'];
if (isset($accessToken))
{
 if (!isset($_SESSION['facebook_access_token']))
 {
  //get 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']);
 }
 else
 {
  $fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
 }
 //redirect the user to the index page if it has $_GET['code']
 if (isset($_GET['code']))
 {
  header('Location: ./');
 }
 try {
  $fb_response = $fb->get('/me?fields=name,first_name,last_name,email');
  $fb_response_picture = $fb->get('/me/picture?redirect=false&height=200');
  $fb_user = $fb_response->getGraphUser();
  $picture = $fb_response_picture->getGraphUser();
  $_SESSION['fb_user_id'] = $fb_user->getProperty('id');
  $_SESSION['fb_user_name'] = $fb_user->getProperty('name');
  $_SESSION['fb_user_email'] = $fb_user->getProperty('email');
  $_SESSION['fb_user_pic'] = $picture['url'];
 } catch(Facebook\Exceptions\FacebookResponseException $e) {
  echo 'Facebook API Error: ' . $e->getMessage();
  session_destroy();
  // redirecting user back to app login page
  header("Location: ./");
  exit;
 } catch(Facebook\Exceptions\FacebookSDKException $e) {
  echo 'Facebook SDK Error: ' . $e->getMessage();
  exit;
 }
}
else
{
 $fb_login_url = $fb_helper->getLoginUrl('http://localhost/facebook1/', $permissions);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <title>Login with Facebook</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
  <link href="<?php echo BASE_URL; ?>css/style.css" rel="stylesheet">
</head>
<body>
<div class="page-header text-center">
  <h1>Login with Facebook</h1>
</div>
<?php if(isset($_SESSION['fb_user_id'])): ?>
 <nav class="navbar navbar-expand-sm bg-dark navbar-dark">
   <a class="navbar-brand" href="<?php echo BASE_URL; ?>">HOME</a>
   <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapsibleNavbar">
  <span class="navbar-toggler-icon"></span>
   </button>
   <div class="collapse navbar-collapse" id="collapsibleNavbar">
  <ul class="navbar-nav">
    <li class="nav-item">
   <a class="nav-link" href="https://studio.youtube.com/channel/UCOXYfOHgu-C-UfGyDcu5sYw"><i class="fa fa-youtube"> YouTube Chanel</i></a>
    </li>
    <li class="nav-item">
   <a class="nav-link" href="https://www.facebook.com/ahmadlogs"><i class="fa fa-facebook">acebook</i></a>
    </li>
    <li class="nav-item">
   <a class="nav-link" href="https://github.com/ahmadlogs/"><i class="fa fa-github"> GitHub</i></a>
    </li>
    <li class="nav-item">
   <a class="nav-link" href="logout.php">Logout</a>
    </li>
  </ul>
   </div>
 </nav>
 <div class="container" style="margin-top:30px">
   <div class="row">
  <div class="col-sm-2">
    <h2>About Me</h2>
    <h5>Profile Picture:</h5>
    <div class="fakeimg"><?php echo $_SESSION['fb_user_pic']; ?></div>
    <hr class="d-sm-none">
  </div>
  <div class="col-sm-2"></div>
  <div class="col-sm-8">
    <h3>User Info</h3>
    <ul class="nav nav-pills flex-column">
   <li class="nav-item">
     <a class="nav-link" >Facebook ID: <?php echo $_SESSION['fb_user_id']; ?></a>
   </li>
   <li class="nav-item">
     <a class="nav-link">Full Name: <?php echo $_SESSION['fb_user_name']; ?></a>
   </li>
   <li class="nav-item">
     <a class="nav-link">Email: <?php echo $_SESSION['fb_user_email']; ?></a>
   </li>
    </ul>
  </div>
   </div>
 </div>
<?php else: ?>
 <div class="login-form">
  <form action="" method="post">
   <h2 class="text-center">Sign in</h2>
   <div class="text-center social-btn">
    <a href="<?php echo $fb_login_url;?>" class="btn btn-primary btn-block"><i class="fa fa-facebook"></i> Sign in with <b>Facebook</b></a>
   </div>
   <div class="or-seperator"><i>or</i></div>
   <div class="form-group">
    <div class="input-group">
     <div class="input-group-prepend">
      <span class="input-group-text"><span class="fa fa-user"></span></span>
     </div>
     <input type="text" class="form-control" name="username" placeholder="Username">
    </div>
   </div>
   <div class="form-group">
    <div class="input-group">
     <div class="input-group-prepend">
      <span class="input-group-text"><i class="fa fa-lock"></i></span>
     </div>
     <input type="password" class="form-control" name="password" placeholder="Password">
    </div>
   </div>
   <div class="form-group">
    <button type="submit" class="btn btn-success btn-block login-btn">Sign in</button>
   </div>
   <div class="clearfix">
    <label class="float-left form-check-label"><input type="checkbox"> Remember me</label>
    <a href="#" class="float-right text-success">Forgot Password?</a>
   </div>
  </form>
  <div class="hint-text">Don't have an account? <a href="#" class="text-success">Register Now!</a></div>
 </div>
<?php endif ?>
</body>
</html>
  1. Include the config.php file with in require_once
  2. If- else statement created for check if the $accessToken is valid to see if the account is already logged in or not.
  3. Within the if statement create another if-else statement for if the
  4. $_SESSION of ‘facebook_access_token’ is not valid the get short-lived access token
  5. To get Oauth 2.0 client handler with the getOAuth2Client() function
  6. Exchanges a short-lived access token for a long-lived one by using getLongAccessToken() function.
  7. setting default access token to be used in the script
  8. now within the Else statement setDefaultAccessToken() for login page
  9. redirect the user to the index page if it has $_GET['code']
  10. Create a try-and-catch statement first. Within the try statement create variables for get() the name, response picture, user, and picture. $_SESSION to store the variables.
  11. Catch() if the error happen.
  12. replace your website URL same as added in the developers.Facebook.com/apps by using getLoginUrl()
  13. now creating an HTML page for the user interface of the Facebook login page
  14. attach external stylesheet to add the

Style.css

.fakeimg {
    height: 200px;
    background: #aaa;
  }
.login-form {
    width: 340px;
    margin: 30px auto;
   font-size: 15px;
}
.login-form form {
    margin-bottom: 15px;
    background: #f7f7f7;
    box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3);
    padding: 30px;
}
.login-form h2 {
    margin: 0 0 15px;
}
.login-form .hint-text {
    color: #777;
    padding-bottom: 15px;
    text-align: center;
   font-size: 13px;
}
.form-control, .btn {
    min-height: 38px;
    border-radius: 2px;
}
.login-btn {
    font-size: 15px;
    font-weight: bold;
}
.or-seperator {
    margin: 20px 0 10px;
    text-align: center;
    border-top: 1px solid #ccc;
}
.or-seperator i {
    padding: 0 10px;
    background: #f7f7f7;
    position: relative;
    top: -11px;
    z-index: 1;
}
.social-btn .btn {
    margin: 10px 0;
    font-size: 15px;
    text-align: left;
    line-height: 24px;
}
.social-btn .btn i {
    float: left;
    margin: 4px 15px 0 5px;
    min-width: 15px;
}
.input-group-addon .fa{
    font-size: 18px;
}

Logout.php

<?php
require_once 'config.php';
unset($_SESSION['facebook_access_token']);
unset($_SESSION['fb_user_id']);
unset($_SESSION['fb_user_name']);
unset($_SESSION['fb_user_email']);
unset($_SESSION['fb_user_pic']);
header("Location:index.php");
?>
  1. for log out page, include ‘config.php’ by using require_once ()
  2. unset() function to unset the $_SESSION of user id, user name, user email and user pic.
  3. Adding a Header() function with the location of index.php

Conclusion :-

At last, here in conclusion, here we can say that with this article’s help, we know to login with facebook using PHP.

I hope this article on login with facebook in php helps you and the steps and method mentioned above are easy to follow and implement.

Author Image About Amruta

Amruta is an Experienced web developer with 4 years for experience she completed her master's with MCA and passionate about programming Languages for creating technical contents like HTML, CSS, JavaScript, Java, Python, PHP, jQuery.

Follow Amruta On Linkedin 🡪