Dear Reader, let us we know that “How to create a facebook login in PHP“. So in this Tutorial, We Learn Step By Step facebook login Process in PHP.
Login and Registration is the very common requirement. In other words, we can say Login and Registration are very necessary for websites and applications. Visitors do not want to fill the registration form and wants an easy process for the same.
In this tutorial, We are going to Implement Login and Registration in a single click with the help of Facebook SDK. Facebook is the most Powerfull Social Network and everybody has the account on there. In this tutorial on a single click, we will store the user details in the database.
Now let’s start Facebook Login Process in step by step.
First, we see Snapshot for the facebook login button
Step 1:- First of all we need to create a Facebook App from
How to Create Facebook App and App Secret
Step 2:- Please download Facebook SDK from here
Step 3:- Now we need to create the database like “php_demo”
Step 4:- Now create a table “users” in a database using the below SQL code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
CREATE TABLE `users` ( `id` int(11) NOT NULL AUTO_INCREMENT, `oauth_provider` enum('','facebook','google','twitter') COLLATE utf8_unicode_ci NOT NULL, `oauth_uid` varchar(100) COLLATE utf8_unicode_ci NOT NULL, `first_name` varchar(50) COLLATE utf8_unicode_ci NOT NULL, `last_name` varchar(50) COLLATE utf8_unicode_ci NOT NULL, `email` varchar(100) COLLATE utf8_unicode_ci NOT NULL, `gender` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL, `locale` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL, `cover` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, `picture` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `link` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `created` datetime NOT NULL, `modified` datetime NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; |
Step 5:- Now we need to create a user_config.php file in the root directory and paste the below code
like “http://localhost/php_demo/login-with-fb/user_config.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 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 |
<?php class User { private $dbHost = "localhost"; private $dbUsername = "root"; private $dbPassword = ""; private $dbName = "php_demo"; private $userTbl = 'users'; function __construct() { if(!isset($this->db)) { // Connect to the database $conn = new mysqli($this->dbHost, $this->dbUsername, $this->dbPassword, $this->dbName); if($conn->connect_error){ die("Failed to connect with MySQL: " . $conn->connect_error); }else{ $this->db = $conn; } } } function checkUser($userData = array()) { if(!empty($userData)){ // Check whether user data already exists in database $prevQuery = "SELECT * FROM ".$this->userTbl." WHERE oauth_provider = '".$userData['oauth_provider']."' AND oauth_uid = '".$userData['oauth_uid']."' "; $prevResult = $this->db->query($prevQuery); if($prevResult->num_rows > 0) { // Update user data if already exists $query = "UPDATE ".$this->userTbl." SET first_name = '".$userData['first_name']."', last_name = '".$userData['last_name']."', email = '".$userData['email']."', gender = '".$userData['gender']."', locale = '".$userData['locale']."', cover = '".$userData['cover']."', picture = '".$userData['picture']."', link = '".$userData['link']."', modified = NOW() WHERE oauth_provider = '".$userData['oauth_provider']."' AND oauth_uid = '".$userData['oauth_uid']."' "; $update = $this->db->query($query); } else { // insert user data $query = "INSERT INTO ".$this->userTbl." SET oauth_provider = '".$userData['oauth_provider']."', oauth_uid = '".$userData['oauth_uid']."', name = '".$userData['first_name'].' '.$userData['last_name']."', email = '".$userData['email']."', gender = '".$userData['gender']."', locale = '".$userData['locale']."', cover = '".$userData['cover']."', picture = '".$userData['picture']."', link = '".$userData['link']."', created_date = NOW(), modified_date = NOW(), is_active = '1' "; $insert = $this->db->query($query); } // Get user data from the database $result = $this->db->query($prevQuery); $userData = $result->fetch_assoc(); } // return user data return $userData; } } ?> |
Step 6:- Now we need to create an index.php file in the root directory and paste the below code
like “http://localhost/php_demo/login-with-fb/index.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 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 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 |
<?php // Include FB config file && User class require_once 'fb_config.php'; require_once 'user_config.php'; if(isset($accessToken)){ if(isset($_SESSION['facebook_access_token'])){ $fb->setDefaultAccessToken($_SESSION['facebook_access_token']); }else{ // Put short-lived access token in session $_SESSION['facebook_access_token'] = (string) $accessToken; // OAuth 2.0 client handler helps to manage access tokens $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; // Set default access token to be used in script $fb->setDefaultAccessToken($_SESSION['facebook_access_token']); } // Redirect the user back to the same page if url has "code" parameter in query string if(isset($_GET['code'])){ header('Location: ./'); } // Getting user facebook profile info try { $profileRequest = $fb->get('/me?fields=name,first_name,last_name,email,link,gender,locale,cover,picture'); $fbUserProfile = $profileRequest->getGraphNode()->asArray(); } catch(FacebookResponseException $e) { echo 'Graph returned an error: ' . $e->getMessage(); session_destroy(); // Redirect user back to app login page header("Location: ./"); exit; } catch(FacebookSDKException $e) { echo 'Facebook SDK returned an error: ' . $e->getMessage(); exit; } // Initialize User class $user = new User(); // Insert or update user data to the database $fbUserData = array( 'oauth_provider'=> 'facebook', 'oauth_uid' => $fbUserProfile['id'], 'first_name' => $fbUserProfile['first_name'], 'last_name' => $fbUserProfile['last_name'], 'email' => $fbUserProfile['email'], 'gender' => $fbUserProfile['gender'], 'locale' => $fbUserProfile['locale'], 'cover' => $fbUserProfile['cover']['source'], 'picture' => $fbUserProfile['picture']['url'], 'link' => $fbUserProfile['link'] ); $userData = $user->checkUser($fbUserData); // Put user data into session $_SESSION['userData'] = $userData; // Get logout url $logoutURL = $helper->getLogoutUrl($accessToken, $redirectURL.'logout.php'); // Render facebook profile data //print_r($userData); if(!empty($userData)){ $output = '<h2 style="color:#999999;">Facebook Profile Details</h2>'; $output .= '<div style="position: relative;">'; $output .= '<img src="'.$userData['cover'].'" />'; $output .= '<img style="position: absolute; top: 90%; left: 25%;" src="'.$userData['picture'].'"/>'; $output .= '</div>'; $output .= '<br/>Facebook ID : '.$userData['oauth_uid']; $output .= '<br/>Name : '.$userData['first_name'].' '.$userData['last_name']; $output .= '<br/>Email : '.$userData['email']; $output .= '<br/>Gender : '.$userData['gender']; $output .= '<br/>Locale : '.$userData['locale']; $output .= '<br/>Logged in with : Facebook'; $output .= '<br/>Profile Link : <a href="'.$userData['link'].'" target="_blank">Click to visit Facebook page</a>'; $output .= '<br/>Logout from <a href="'.$logoutURL.'">Facebook</a>'; header("Location:index.php"); } else{ $output = '<h3 style="color:red">Some problem occurred, please try again.</h3>'; } }else{ // Get login url $loginURL = $helper->getLoginUrl($redirectURL, $fbPermissions); // Render facebook login button $output = '<a href="'.htmlspecialchars($loginURL).'"><img src="images/fblogin-btn.png"></a>'; $output = '<a href="'.htmlspecialchars($loginURL).'"></a>'; } ?> <!DOCTYPE html> <html lang="en"> <head> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> </head> <body> <br><br><br> <div class="container"> <h2 class="alert alert-info">How to create facebook login in php</h2> <center> <div class="row"> <div><?php echo $output; ?></div> </div> </center> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> </body> </html> |
Step 7:- Now we need to create a fb_config.php file in the root directory and paste the below code
like “http://localhost/php_demo/login-with-fb/fb_config.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 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 |
<?php if(!session_id()) { session_start(); } // Include the autoloader provided in the SDK require_once __DIR__ . '/facebook-php-sdk/autoload.php'; // Include required libraries use Facebook\Facebook; use Facebook\Exceptions\FacebookResponseException; use Facebook\Exceptions\FacebookSDKException; /* here you need to configure app detail*/ $appId = '2087986308156790'; //facebook app id $appSecret = '52646f7494ae89d76420ace1025a0f0b'; //facebook app secret $redirectURL = 'http://www.webpreparations/demo/login-with-facebook/index.php'; //Callback URL $fbPermissions = array('email'); //Optional permissions $fb = new Facebook(array( 'app_id' => $appId, 'app_secret' => $appSecret, 'default_graph_version' => 'v2.2', )); // here you will be redirect to helper $helper = $fb->getRedirectLoginHelper(); // Try to get access token try { if(isset($_SESSION['facebook_access_token'])) { $accessToken = $_SESSION['facebook_access_token']; } else { $accessToken = $helper->getAccessToken(); } } catch(FacebookResponseException $e) { echo 'Graph returned an error: ' . $e->getMessage(); exit; } catch(FacebookSDKException $e) { echo 'Facebook SDK returned an error: ' . $e->getMessage(); exit; } ?> |
Step 8:- At last we need to create a logout.php file in the root directory and paste the below code
1 2 3 4 5 6 7 8 9 10 |
<?php // include FB config file include_once 'fb_config.php'; // remove access token from session unset($_SESSION['facebook_access_token']); // remove user data from session unset($_SESSION['userData']); // Redirect to the homepage header("Location:index.php"); ?> |
Step 9:- Now run your project, so we need to type in browser localhost/your_project_name/index.php
like
“http://localhost/php_demo/login-with-fb/index.php” then you can see the result as in below snapshot, you can click on facebook login
Congratulations you have successfully created “How to create a facebook login in PHP”, if you like this post and was helpful for you then share this post on social media and if you have any query then please contact us or comment below, Thanks.
4 Comments:
Farah September 19, 2018
Very Good article.
Very help full.
Keep it up..
Webpreparations Team September 19, 2018
Thank you so much for your appreciation 🙂
ummed June 28, 2019
Thanks for the code-
“How to create facebook login in php”
WebPreparations Team July 06, 2019
Thank you for your appreciation and always welcome.