Tuesday 25 September 2018

Login with Facebook using PHP and MySQL

Registration through filling a long form is a headache to any user. After seeing such big form they run away. But short registration process helps to get more subscribers for your website. Meanwhile, Facebook is the largest social network in Earth and billions of users. Facebook provides PHP SDK through which you can easily integrate registration and login system on your website. Facebook login will allow users to login into your website using their Facebook account credentials without registration into your website. For doing login with Facebook you need a Facebook App ID and a secret key.

In this tutorial, I will show you how you can implement user Login with Facebook using PHP and MySQL and store the user’s profile data into MySQL database. We will use Facebook PHP SDK v5.0 to implement Login with Facebook into the website.

The latest version of Facebook PHP SDK v5.0 requires the following two requirements —
  1. PHP version should be 5.4 or greater.
  2. The php_mbstring extension should be enabled.

Database Table

  1. CREATE TABLE `oauth_users` (
  2. `id` int(11) NOT NULL,
  3. `oauth_provider` varchar(50) NOT NULL,
  4. `oauth_id` varchar(100) NOT NULL,
  5. `name` varchar(100) NOT NULL,
  6. `first_name` varchar(50) NOT NULL,
  7. `last_name` varchar(50) NOT NULL,
  8. `email` varchar(100) NOT NULL,
  9. `gender` varchar(10) NOT NULL,
  10. `locale` varchar(10) NOT NULL,
  11. `picture` varchar(255) NOT NULL,
  12. `link` varchar(255) NOT NULL,
  13. `created` datetime NOT NULL,
  14. `modified` datetime NOT NULL
  15. )
To store the user’s information you need a MySQL table. Run the above query and create the table.

Facebook PHP SDK v5.0

Download the latest version of Facebook PHP SDK from github.com. Whatever, the Facebook PHP SDK v5.0 is already included in source code folder, you can download it from the below download link.

Facebook PHP SDK Configuration (config.php)

  1. <?php
  2. session_start();
  3. require_once __DIR__ . '/Facebook/autoload.php';
  4. // Include required libraries
  5. use Facebook\Facebook;
  6. use Facebook\Exceptions\FacebookResponseException;
  7. use Facebook\Exceptions\FacebookSDKException;
  8. //Configuration of the Facebook SDK
  9. $redirectUrl = 'http://localhost/mit-demos/facebook-login/';
  10. $fb = new Facebook([
  11. 'app_id' => 'replace_with_your_facebook_app_id',
  12. 'app_secret' => 'replace_with_your_facebook_app_secret_key',
  13. 'default_graph_version' => 'v2.2',
  14. ]);
  15. //Get the login redirect helper
  16. $helper = $fb->getRedirectLoginHelper();
  17. if (isset($_GET['state'])) {
  18. $helper->getPersistentDataHandler()->set('state', $_GET['state']);
  19. }
  20. //Get the access token
  21. try {
  22. if(isset($_SESSION['facebook_access_token'])) {
  23. $accessToken = $_SESSION['facebook_access_token'];
  24. } else {
  25. $accessToken = $helper->getAccessToken();
  26. }
  27. }catch(Facebook\Exceptions\FacebookResponseException $e) {
  28. // When Graph returns an error
  29. echo 'Graph error: ' . $e->getMessage();
  30. exit;
  31. } catch(Facebook\Exceptions\FacebookSDKException $e) {
  32. // When validation fails or other local issues
  33. echo 'Facebook SDK error: ' . $e->getMessage();
  34. exit;
  35. }
  36. ?>
In the config.php file, you need to configure some parameters to get it working. You need to set app_id,  app_secret with your Facebook App ID and secret key. Change the $redirectUrl with yours.

Login (index.php)

  1. <?php include('config.php'); ?>
  2. <?php include('oauth-user.php'); ?>
  3. <style>
  4. .login_image {
  5. display:block;
  6. margin:auto;
  7. position:absolute;
  8. top:0;
  9. right:0;
  10. bottom:0;
  11. left:0;
  12. height:100px;
  13. width:300px;
  14. }
  15. </style>
  16. <?php
  17. //If no $accessToken is set then user should log in first
  18. if(isset($accessToken)) {
  19. if(isset($_SESSION['facebook_access_token'])){
  20. $fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
  21. } else {
  22. //Put short-lived access token in session
  23. $_SESSION['facebook_access_token'] = (string) $accessToken;
  24. //The OAuth 2.0 client handler helps us manage access tokens
  25. $oAuth2Client = $fb->getOAuth2Client();
  26. if(!$accessToken->isLongLived()) {
  27. //Exchanges a short-lived access token for a long-lived one
  28. try {
  29. $accessToken = $oAuth2Client->getLongLivedAccessToken($accessToken);
  30. $_SESSION['facebook_access_token'] = (string) $accessToken;
  31. } catch (Facebook\Exceptions\FacebookSDKException $e) {
  32. echo "<p>Error getting long-lived access token: " . $helper->getMessage() . "</p>\n\n";
  33. exit;
  34. }
  35. }
  36. }
  37. //Redirect user to the index page if url has "code" parameter in query string
  38. if(isset($_GET['code'])){
  39. header('location: ./');
  40. }
  41. //Getting user's facebook profile information
  42. try {
  43. $profileRequest = $fb->get('/me?fields=name,first_name,last_name,email,link,gender,locale,picture');
  44. $fbUserData = $profileRequest->getGraphNode()->asArray();
  45. //Ceate an instance of the OauthUser class
  46. $oauth_user_obj = new OauthUser();
  47. $userData = $oauth_user_obj->verifyUser($fbUserData);
  48. } catch(FacebookResponseException $e) {
  49. echo 'Graph returned an error: ' . $e->getMessage();
  50. session_destroy();
  51. //Redirect user to the index page
  52. header("Location: ./");
  53. exit;
  54. } catch(FacebookSDKException $e) {
  55. echo 'Facebook SDK returned an error: ' . $e->getMessage();
  56. session_destroy();
  57. //Redirect user to the index page
  58. header("Location: ./");
  59. exit;
  60. }
  61. } else {
  62. //Get login url
  63. $loginUrl = $helper->getLoginUrl($redirectUrl);
  64. echo '<a href="'.htmlspecialchars($loginUrl).'"><img class="login_image" src="images/fblogin-btn.png"></a>';
  65. }
  66. ?>
If the user is not logged in then a Login with Facebook button will display. After clicking on the Login with Facebook button Facebook login page will display, input credentials and login.
  1. $profileRequest = $fb->get('/me?fields=name,first_name,last_name,email,link,gender,locale,picture');
  2. $fbUserData = $profileRequest->getGraphNode()->asArray();
  3. //Ceate an instance of the OauthUser class
  4. $oauth_user_obj = new OauthUser();
  5. $userData = $oauth_user_obj->verifyUser($fbUserData);
The first two line gets facebook user’s information such as namefirst_name,  email and so on as an array. The last two lines create an instance of the OauthUser class and pass the array of user’s data into it.

Verify User’s Data (OauthUser.php)

  1. <?php
  2. class OauthUser {
  3. private $host = "localhost";
  4. private $username = "root";
  5. private $password = "";
  6. private $database_name = "your_databasename";
  7. private $table = 'oauth_users';
  8. private $db;
  9. function __construct(){
  10. // Connect to the MySQL database
  11. $this->db = new mysqli($this->host, $this->username, $this->password, $this->database_name);
  12. if($con->connect_error){
  13. die("Failed to connect with MySQL database: " . $this->db->connect_error);
  14. }
  15. }
  16. function verifyUser($userInfo) {
  17. $qry_body = " `oauth_provider` = 'facebook',
  18. `oauth_id` = '".$userInfo['id']."',
  19. `name` = '".$userInfo['name']."',
  20. `first_name` = '".$userInfo['first_name']."',
  21. `last_name` = '".$userInfo['last_name']."',
  22. `email` = '".$userInfo['email']."',
  23. `gender` = '".$userInfo['gender']."',
  24. `locale` = '".$userInfo['locale']."',
  25. `picture` = '".$userInfo['picture']['url']."',
  26. `link` = '".$userInfo['link']."',
  27. `modified` = '".date("Y-m-d H:i:s")."' ";
  28. $select_qry = "select * from `oauth_users` where `oauth_provider`='facebook' and `oauth_id`= '".$userInfo['id']."'";
  29. $res = $this->db->query($select_qry);
  30. if($res->num_rows > 0) {
  31. //Update user details if it is already exists in the table
  32. $qry = "update ".$this->table." set ".$qry_body." WHERE `oauth_provider` = 'facebook' AND `oauth_id` = '".$userInfo['id']."'";
  33. } else {
  34. //Insert into table if user not exists in the table
  35. $qry = "insert into ".$this->table." set ".$qry_body.", `created`='".date("Y-m-d H:i:s")."'";
  36. }
  37. $this->db->query($qry);
  38. if($this->db->affected_rows == 1) {
  39. $_SESSION['user_is_login'] = true;
  40. $_SESSION['user_id'] = $userInfo['id'];
  41. $_SESSION['user_name'] = $userInfo['name'];
  42. $_SESSION['user_fname'] = $userInfo['first_name'];
  43. $_SESSION['user_lname'] = $userInfo['last_name'];
  44. $_SESSION['user_email'] = $userInfo['email'];
  45. $_SESSION['user_gender'] = $userInfo['gender'];
  46. $_SESSION['user_picture'] = $userInfo['picture']['url'];
  47. $_SESSION['user_link'] = $userInfo['link'];
  48. header('location:welcome.php');
  49. exit();
  50. }
  51. }
  52. }
  53. ?>
OauthUser.php file receives user’s data from index.php and verify it, whether the user already exists or not in the table. If not exists, then a fresh new insert will do otherwise it updates the existing record. After successful insert or update, we will store user’s data into session and then redirect it to the welcome.php page.

Profile Display (welcome.php)

  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3. <head>
  4. <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
  5. <title>Welcome | Mitrajit's Tech Blog</title>
  6. <style>
  7. body, html {
  8. padding:0;
  9. margin:0;
  10. }
  11. .header {
  12. border:1px solid #ccc;
  13. background-color:#FF9900;
  14. }
  15. .header ul {
  16. float:right;
  17. margin-right:5px;
  18. }
  19. .header ul li {
  20. display:inline-table;
  21. list-style:none;
  22. }
  23. .clearfix {
  24. clear:both;
  25. }
  26. h2 {
  27. text-align:center;
  28. }
  29. h1 {
  30. width: 215px;
  31. float: left;
  32. font-size: 20px;
  33. margin-left: 10px;
  34. }
  35. h1 a {
  36. font-size:20px;
  37. color:#fff;
  38. text-decoration:none;
  39. }
  40. ul a {
  41. color:#fff;
  42. text-decoration:none;
  43. }
  44. ul a:hover {
  45. text-decoration:underline;
  46. }
  47. .content {
  48. margin: 0 auto;
  49. width: 500px;
  50. margin-top: 100px;
  51. }
  52. table {
  53. border:1px solid #000;
  54. }
  55. img {
  56. border: 2px solid #ccc;
  57. padding: 2px;
  58. }
  59. </style>
  60. </head>
  61. <?php session_start(); ?>
  62. <?php
  63. if(!isset($_SESSION['user_is_login']) || @$_SESSION['user_is_login'] == false) {
  64. header('location:index2.php');
  65. }
  66. ?>
  67. <body>
  68. <div class="header">
  69. <h1><a href="http://www.mitrajit.com/">Mitrajit's Tech Blog</a></h1>
  70. <ul>
  71. <li><a href="<?php echo @$_SESSION['user_link'];?>" target="_blank"><div><?php echo @$_SESSION['user_name'];?></div></a></li>
  72. <li>|</li>
  73. <li><a href="logout.php">Logout</a></li>
  74. </ul>
  75. <div class="clearfix"></div>
  76. </div>
  77. <div class="content">
  78. <h2>Facebook user information from Facebook</h2>
  79. <table width="500" border="0">
  80. <tr>
  81. <th rowspan="3" scope="row"><img src="<?php echo $_SESSION['user_picture'];?>" /></th>
  82. <td>Name</td>
  83. <td>:</td>
  84. <td><?php echo $_SESSION['user_name'];?></td>
  85. </tr>
  86. <tr>
  87. <td>First Name </td>
  88. <td>:</td>
  89. <td><?php echo $_SESSION['user_fname'];?></td>
  90. </tr>
  91. <tr>
  92. <td>Last Name </td>
  93. <td>:</td>
  94. <td><?php echo $_SESSION['user_lname'];?></td>
  95. </tr>
  96. <tr>
  97. <th scope="row"> </th>
  98. <td>Email</td>
  99. <td>:</td>
  100. <td><?php echo $_SESSION['user_email'];?></td>
  101. </tr>
  102. <tr>
  103. <th scope="row"> </th>
  104. <td>Gender</td>
  105. <td>:</td>
  106. <td><?php echo $_SESSION['user_gender'];?></td>
  107. </tr>
  108. <tr>
  109. <th scope="row"> </th>
  110. <td>Facebook Link</td>
  111. <td>:</td>
  112. <td><a href="<?php echo $_SESSION['user_link'];?>" target="_blank">Link</a></td>
  113. </tr>
  114. </table>
  115. </div>
  116. </body>
  117. </html>
After login, welcome.php file will display the user’s information.

Logout (logout.php)

  1. <?php
  2. session_destroy();
  3. // Redirect to the homepage
  4. header("location: ./");
  5. ?>
logout.php clear or destroy all the existing sessions.
Hope you enjoyed the tutorial Login with Facebook using PHP and MySQL. You can download the complete source code from the below download link and please like and share the tutorial link to others.

0 comments:

Post a Comment