Login with Facebook using PHP
PHP Facebook Graph API allows users to login in a web application with Facebook credentials. In this tutorial, you will learn how to build a Login with Facebook Account using PHP. This is a very simple example, you can just copy-paste, and change according to your requirement.
Before starting to implement the Login with Facebook using PHP, look files structure:
- login-facebook
- css
- templates
- vendor
- config.php
- index.php
- profile.php
- menus.php.php
Step 1: Login to Facebook Developers
Go to the Facebook Developers Apps and Log In with your Facebook ID.
Step 2: Create an App
Click on the Create App button
Step 3 – Advanced Setting
Goto
Setting >> Advanced
and add redirect URL:Step 4 – Add valid auth URL
Add valid auth redirect URL. So, click
Facebook Login >> Setting
and add valid auth redirect URL:Step 5: get app key and secret key
Finally, get app key and secret key
Setting >> Basic
Install the Facebook PHP SDK Library
Install it using
Composer
1 2 |
//Use Composer $composer require facebook/graph-sdk |
Step 6: Create Config file
Create file named
config.php
In this file, we will put the facebook app key and secret key
1 2 3 4 5 6 |
<?php session_start(); define("APP_KEY", "596098671540591"); define("APP_SECRET_KEY", "7ab3e63b40d420836dd44736af99017e"); define("APP_GRAPH_VERSION", "v2.10"); ?> |
Step 7: Create file index.php
Create an
index.php
file. In this PHP file we will show the facebook login.
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 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 |
<?php include 'config.php'; include('templates/header.php'); //load facebook sdk require 'vendor/autoload.php'; $fb = new Facebook\Facebook([ // FACEBOOK APP KEY 'app_id' => APP_KEY, // FACEBOOK APP SECRET KEY 'app_secret' => APP_SECRET_KEY, // FACEBOOK APP GRAPH VERSION 'default_graph_version' => APP_GRAPH_VERSION, ]); $helper = $fb->getRedirectLoginHelper(); $permissions = ['email']; // Optional permissions 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)) { // Logged in! if (isset($_SESSION['facebook_access_token'])) { //Now you can redirect to another page and use the $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 account page if it has "code" GET variable if (isset($_GET['code'])) { header('Location: https://techarise.com/demos/php/login-facebook/acount.php'); } // getting basic info about user try { $account_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(); $account = $account_request->getGraphUser(); $fbid = $account->getProperty('id'); // To Get Facebook ID $fbfullname = $account->getProperty('name'); // To Get Facebook full name $fbemail = $account->getProperty('email'); // To Get Facebook email $fbpicture = "<img src='" . $picture['url'] . "' class='img-rounded'/>"; # save the user nformation in session variable $_SESSION['fb_id'] = $fbid . '</br>'; $_SESSION['fb_fullname'] = $fbfullname . '</br>'; $_SESSION['fb_email'] = $fbemail . '</br>'; $_SESSION['fb_picture'] = $fbpicture . '</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: index.php"); exit; } catch (Facebook\Exceptions\FacebookSDKException $e) { // validation fails or other issues echo 'Facebook SDK returned an error: ' . $e->getMessage(); exit; } } else { // replace your web application URL same as added in the developers.Facebook.com/apps $facebookLoginURL = $helper->getLoginUrl('https://techarise.com/demos/php/login-facebook', $permissions); ?> <main role="main" class="container mcontainer"> <div class="wrapper"> <form action="" method="post" id="loginform" name="Login_Form" class="form-signin" method="POST"> <h3 class="form-signin-heading">Welcome to Login with Facebook </h3> <input type="email" class="form-control" id="email" name="email" placeholder="Email*" required /> <input type="password" class="form-control" id="password" name="password" placeholder="*****" required /> <button type="submit" name="login" class="btn btn-lg btn-info" style="float:left">Login</button> <a href="<?php print $facebookLoginURL; ?>" class="btn btn-lg btn-primary" style="float:right"><i class="fa fa-facebook"></i> Login with Facebook</a> </form> </div> </main> <?php } ?> <?php include('templates/footer.php'); ?> |
Step 8: Create a profile.php
Create a
profile.php
file. In this file, we will show logged in user information like name, email, profile image and more.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
<?php include 'config.php'; include('templates/header.php'); ?> <!-- Begin page content --> <main role="main" class="container mcontainer"> <div class="row home-sections"> <h2>Login with Facebook using PHP</h2> </div> <section class="comment-list"> <article class="row"> <?php if ($_SESSION['fb_id']) { ?> <h3>Hello, <?php echo $_SESSION['fb_fullname']; ?></h3> <div style="padding: 10px"> <h5><strong>Profile Image: </strong><?php echo $_SESSION['fb_picture'] ?></h5> <h5><strong>Name: </strong><?php echo $_SESSION['fb_fullname']; ?></h5> <h5><strong>Email: </strong><?php echo $_SESSION['fb_email']; ?></h5> </div> <?php } ?> </article> </section> </main> <?php include('templates/footer.php'); ?> |
Create files named (header.php and footer.php)
This file contains the header and footer section of the webpage. The Bootstrap library is used to provide a better UI, so, include it in the header and footer section.
header.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
<!doctype html> <html lang="en"> <head> <link rel="canonical" href="https://techarise.com/" /> <meta name="author" content="TechArise"> <meta name="description" content="Learn Web Development Tutorials & Web Developer Resources, PHP, MySQL, jQuery, CSS, XHTML, jQuery UI, CSS3, HTML5, HTML, web design, webdesign, with TechArise tutorials. View live demo"> <meta name="keywords" content="TechArise, tutorial TechArise, tutorials, freebies, resources, web development, webdev, demo, PHP, MySQL, jQuery, CSS, XHTML, jQuery UI, CSS3, HTML5, HTML, web design, webdesign, php script, dynamic web content" /> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="icon" type="image/ico" href="https://techarise.com/wp-content/themes/v1/favicon.ico"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"> <link href="http://maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css" rel="stylesheet"> <link rel="stylesheet" href="https://cdn.datatables.net/responsive/2.2.9/css/responsive.bootstrap4.min.css" /> <link rel="stylesheet" href="https://cdn.datatables.net/1.11.3/css/dataTables.bootstrap4.min.css" /> <!--- Custom css ---> <link rel="stylesheet" href="css/style.css" /> <title>Login with Facebook using PHP | Tech Arise</title> </head> <body> <?php include('menus.php'); ?> |
menus.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
<header> <!-- Fixed navbar --> <nav class="navbar navbar-expand-md navbar-dark fixed-top bg-dark" style="background: #273E4A!important;"> <a class="navbar-brand" href="https://techarise.com"><strong>Tech Arise</strong></a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarCollapse"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="https://techarise.com">Home <span class="sr-only">(current)</span></a> </li> </ul> <span class="nav-item dropdown"> <a style="color:#fff;" class="nav-link" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> <i class="fa fa-facebook"></i> Login </a> </span> </div> </nav> </header> |
footer.php
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<footer class="footer"> <div class="container"> </div> </footer> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script> <script src="https://cdn.datatables.net/1.11.3/js/jquery.dataTables.min.js"></script> <script src="https://cdn.datatables.net/1.11.3/js/dataTables.bootstrap4.min.js"></script> <script src="https://cdn.datatables.net/responsive/2.2.9/js/dataTables.responsive.min.js"></script> <script src="https://cdn.datatables.net/responsive/2.2.9/js/responsive.bootstrap4.min.js"></script> </body> </html> |