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.
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 —
- PHP version should be 5.4 or greater.
- The php_mbstring extension should be enabled.
Database Table
- CREATE TABLE `oauth_users` (
- `id` int(11) NOT NULL,
- `oauth_provider` varchar(50) NOT NULL,
- `oauth_id` varchar(100) NOT NULL,
- `name` varchar(100) NOT NULL,
- `first_name` varchar(50) NOT NULL,
- `last_name` varchar(50) NOT NULL,
- `email` varchar(100) NOT NULL,
- `gender` varchar(10) NOT NULL,
- `locale` varchar(10) NOT NULL,
- `picture` varchar(255) NOT NULL,
- `link` varchar(255) NOT NULL,
- `created` datetime NOT NULL,
- `modified` datetime NOT NULL
- )
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)
- <?php
- session_start();
- require_once __DIR__ . '/Facebook/autoload.php';
- // Include required libraries
- use Facebook\Facebook;
- use Facebook\Exceptions\FacebookResponseException;
- use Facebook\Exceptions\FacebookSDKException;
- //Configuration of the Facebook SDK
- $redirectUrl = 'http://localhost/mit-demos/facebook-login/';
- $fb = new Facebook([
- 'app_id' => 'replace_with_your_facebook_app_id',
- 'app_secret' => 'replace_with_your_facebook_app_secret_key',
- 'default_graph_version' => 'v2.2',
- ]);
- //Get the login redirect helper
- $helper = $fb->getRedirectLoginHelper();
- if (isset($_GET['state'])) {
- $helper->getPersistentDataHandler()->set('state', $_GET['state']);
- }
- //Get the access token
- 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 error: ' . $e->getMessage();
- exit;
- } catch(Facebook\Exceptions\FacebookSDKException $e) {
- // When validation fails or other local issues
- echo 'Facebook SDK error: ' . $e->getMessage();
- exit;
- }
- ?>
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)
- <?php include('config.php'); ?>
- <?php include('oauth-user.php'); ?>
- <style>
- .login_image {
- display:block;
- margin:auto;
- position:absolute;
- top:0;
- right:0;
- bottom:0;
- left:0;
- height:100px;
- width:300px;
- }
- </style>
- <?php
- //If no $accessToken is set then user should log in first
- 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;
- //The OAuth 2.0 client handler helps us manage access tokens
- $oAuth2Client = $fb->getOAuth2Client();
- if(!$accessToken->isLongLived()) {
- //Exchanges a short-lived access token for a long-lived one
- try {
- $accessToken = $oAuth2Client->getLongLivedAccessToken($accessToken);
- $_SESSION['facebook_access_token'] = (string) $accessToken;
- } catch (Facebook\Exceptions\FacebookSDKException $e) {
- echo "<p>Error getting long-lived access token: " . $helper->getMessage() . "</p>\n\n";
- exit;
- }
- }
- }
- //Redirect user to the index page if url has "code" parameter in query string
- if(isset($_GET['code'])){
- header('location: ./');
- }
- //Getting user's facebook profile information
- try {
- $profileRequest = $fb->get('/me?fields=name,first_name,last_name,email,link,gender,locale,picture');
- $fbUserData = $profileRequest->getGraphNode()->asArray();
- //Ceate an instance of the OauthUser class
- $oauth_user_obj = new OauthUser();
- $userData = $oauth_user_obj->verifyUser($fbUserData);
- } catch(FacebookResponseException $e) {
- echo 'Graph returned an error: ' . $e->getMessage();
- session_destroy();
- //Redirect user to the index page
- header("Location: ./");
- exit;
- } catch(FacebookSDKException $e) {
- echo 'Facebook SDK returned an error: ' . $e->getMessage();
- session_destroy();
- //Redirect user to the index page
- header("Location: ./");
- exit;
- }
- } else {
- //Get login url
- $loginUrl = $helper->getLoginUrl($redirectUrl);
- echo '<a href="'.htmlspecialchars($loginUrl).'"><img class="login_image" src="images/fblogin-btn.png"></a>';
- }
- ?>
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.
- $profileRequest = $fb->get('/me?fields=name,first_name,last_name,email,link,gender,locale,picture');
- $fbUserData = $profileRequest->getGraphNode()->asArray();
- //Ceate an instance of the OauthUser class
- $oauth_user_obj = new OauthUser();
- $userData = $oauth_user_obj->verifyUser($fbUserData);
The first two line gets facebook user’s information such as name, first_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)
- <?php
- class OauthUser {
- private $host = "localhost";
- private $username = "root";
- private $password = "";
- private $database_name = "your_databasename";
- private $table = 'oauth_users';
- private $db;
- function __construct(){
- // Connect to the MySQL database
- $this->db = new mysqli($this->host, $this->username, $this->password, $this->database_name);
- if($con->connect_error){
- die("Failed to connect with MySQL database: " . $this->db->connect_error);
- }
- }
- function verifyUser($userInfo) {
- $qry_body = " `oauth_provider` = 'facebook',
- `oauth_id` = '".$userInfo['id']."',
- `name` = '".$userInfo['name']."',
- `first_name` = '".$userInfo['first_name']."',
- `last_name` = '".$userInfo['last_name']."',
- `email` = '".$userInfo['email']."',
- `gender` = '".$userInfo['gender']."',
- `locale` = '".$userInfo['locale']."',
- `picture` = '".$userInfo['picture']['url']."',
- `link` = '".$userInfo['link']."',
- `modified` = '".date("Y-m-d H:i:s")."' ";
- $select_qry = "select * from `oauth_users` where `oauth_provider`='facebook' and `oauth_id`= '".$userInfo['id']."'";
- $res = $this->db->query($select_qry);
- if($res->num_rows > 0) {
- //Update user details if it is already exists in the table
- $qry = "update ".$this->table." set ".$qry_body." WHERE `oauth_provider` = 'facebook' AND `oauth_id` = '".$userInfo['id']."'";
- } else {
- //Insert into table if user not exists in the table
- $qry = "insert into ".$this->table." set ".$qry_body.", `created`='".date("Y-m-d H:i:s")."'";
- }
- $this->db->query($qry);
- if($this->db->affected_rows == 1) {
- $_SESSION['user_is_login'] = true;
- $_SESSION['user_id'] = $userInfo['id'];
- $_SESSION['user_name'] = $userInfo['name'];
- $_SESSION['user_fname'] = $userInfo['first_name'];
- $_SESSION['user_lname'] = $userInfo['last_name'];
- $_SESSION['user_email'] = $userInfo['email'];
- $_SESSION['user_gender'] = $userInfo['gender'];
- $_SESSION['user_picture'] = $userInfo['picture']['url'];
- $_SESSION['user_link'] = $userInfo['link'];
- header('location:welcome.php');
- exit();
- }
- }
- }
- ?>
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)
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
- <title>Welcome | Mitrajit's Tech Blog</title>
- <style>
- body, html {
- padding:0;
- margin:0;
- }
- .header {
- border:1px solid #ccc;
- background-color:#FF9900;
- }
- .header ul {
- float:right;
- margin-right:5px;
- }
- .header ul li {
- display:inline-table;
- list-style:none;
- }
- .clearfix {
- clear:both;
- }
- h2 {
- text-align:center;
- }
- h1 {
- width: 215px;
- float: left;
- font-size: 20px;
- margin-left: 10px;
- }
- h1 a {
- font-size:20px;
- color:#fff;
- text-decoration:none;
- }
- ul a {
- color:#fff;
- text-decoration:none;
- }
- ul a:hover {
- text-decoration:underline;
- }
- .content {
- margin: 0 auto;
- width: 500px;
- margin-top: 100px;
- }
- table {
- border:1px solid #000;
- }
- img {
- border: 2px solid #ccc;
- padding: 2px;
- }
- </style>
- </head>
- <?php session_start(); ?>
- <?php
- if(!isset($_SESSION['user_is_login']) || @$_SESSION['user_is_login'] == false) {
- header('location:index2.php');
- }
- ?>
- <body>
- <div class="header">
- <h1><a href="http://www.mitrajit.com/">Mitrajit's Tech Blog</a></h1>
- <ul>
- <li><a href="<?php echo @$_SESSION['user_link'];?>" target="_blank"><div><?php echo @$_SESSION['user_name'];?></div></a></li>
- <li>|</li>
- <li><a href="logout.php">Logout</a></li>
- </ul>
- <div class="clearfix"></div>
- </div>
- <div class="content">
- <h2>Facebook user information from Facebook</h2>
- <table width="500" border="0">
- <tr>
- <th rowspan="3" scope="row"><img src="<?php echo $_SESSION['user_picture'];?>" /></th>
- <td>Name</td>
- <td>:</td>
- <td><?php echo $_SESSION['user_name'];?></td>
- </tr>
- <tr>
- <td>First Name </td>
- <td>:</td>
- <td><?php echo $_SESSION['user_fname'];?></td>
- </tr>
- <tr>
- <td>Last Name </td>
- <td>:</td>
- <td><?php echo $_SESSION['user_lname'];?></td>
- </tr>
- <tr>
- <th scope="row"> </th>
- <td>Email</td>
- <td>:</td>
- <td><?php echo $_SESSION['user_email'];?></td>
- </tr>
- <tr>
- <th scope="row"> </th>
- <td>Gender</td>
- <td>:</td>
- <td><?php echo $_SESSION['user_gender'];?></td>
- </tr>
- <tr>
- <th scope="row"> </th>
- <td>Facebook Link</td>
- <td>:</td>
- <td><a href="<?php echo $_SESSION['user_link'];?>" target="_blank">Link</a></td>
- </tr>
- </table>
- </div>
- </body>
- </html>
After login, welcome.php file will display the user’s information.
Logout (logout.php)
- <?php
- session_destroy();
- // Redirect to the homepage
- header("location: ./");
- ?>
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