Nowadays people want easy step to login to your website,People do not like to fill registration form and then login. The shorter way to register is by social media. Login with facebook is popular and authentic way for registration and login system on the website. Facebook is one of the most popular social media network and most of the people use facebook. You can also use facebook login using PHP as login tool where user can login with facebook without sign up on your website.
In this tutorial, we have use latest Facebook API SDK library for login with PHP script.By using Facebook SDK we can easily integrate Facebook login and signup in our website. In this blog We implement user login and registration system with Facebook using PHP and store the user data into the MySQL database.
System Requirement:
- PHP version should be 5.4 or greater
- The mbstring extension should be enabled.
Start With FACEBOOK LOGIN Using PHP
STEP 1: Create Facebook App
To access Facebook API, firstly you have to create Facebook App. Follow the below step to create Facebook App:
- Go to the Facebook for Developers page and log in with your Facebook account.
- Click the My Apps link at the top navigation bar and select Add New App.
- Enter the Display Name and Contact Email.
- Click on the Create App ID button.
- Now, Navigate to the Settings » Basic page.
- Enter App Domains and select the Category of your App.
- Click on Save Changes.
- Go to Product page by clicking the PRODUCTS(+) link at the left navigation menu panel.
- Select Facebook Login to Set Up.
- Select Web as the App platform.
- Enter the Site URL and click to Save Button.
- Go to Facebook Login » Settings page
- In the Valid OAuth Redirect URIs field, enter the Redirect URL.
- Click the Save Changes
Go to setting » Basic page and Copy or note the App ID and App Secret.
STEP 2: Get the Profile Link and Gender
To get the profile link and gender or you want to access user’s Facebook timeline link and gender, then you need to submit a request for user_link and user_gender permissions. How to submit Request follow below steps:
- Go to the App Review » Permissions and Features page.
- Request for user_link and user_gender permissions and submit the required information.
Once Your Request is submitted then wait for the review process is completed by Facebook.
STEP 3: Create Database Table
Now you have to create a database table where you store the User data. we are using table_name ‘users’. The table the basic fields in the MySQL database to hold the Facebook account information.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
CREATE TABLE `users` ( `id` int(11) NOT NULL AUTO_INCREMENT, `oauth_provider` enum('facebook','google','twitter','') COLLATE utf8_unicode_ci NOT NULL DEFAULT '', `oauth_uid` varchar(50) COLLATE utf8_unicode_ci NOT NULL, `first_name` varchar(25) COLLATE utf8_unicode_ci NOT NULL, `last_name` varchar(25) COLLATE utf8_unicode_ci NOT NULL, `email` varchar(25) COLLATE utf8_unicode_ci NOT NULL, `gender` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL, `picture` varchar(200) COLLATE utf8_unicode_ci NOT NULL, `link` varchar(100) 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; |
Facebook SDK for PHP
The facebook-php-chart sdk/registry contains the most recent adaptation (v5) of Facebook SDK for PHP. You don’t have to download it independently, all the required files of Facebook PHP SDK v5 are included in our Facebook Login PHP source code
User Class (User.class.php)
The User class handles the database related activities (connect, insert, and update) using PHP and MySQL. It assists to connect, insert, and update Facebook account information in the users table.
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 |
<?php /* * User Class * This class is used for database related (connect, insert, and update) operations * @author Developerguidance.com * @url http://www.developerguidance.com */ class User { private $dbHost = DB_HOST; private $dbUsername = DB_USERNAME; private $dbPassword = DB_PASSWORD; private $dbName = DB_NAME; private $userTbl = DB_USER_TBL; 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($data = array()){ if(!empty($data)){ // Check whether the user already exists in the database $checkQuery = "SELECT * FROM ".$this->userTbl." WHERE oauth_provider = '".$data['oauth_provider']."' AND oauth_uid = '".$data['oauth_uid']."'"; $checkResult = $this->db->query($checkQuery); // Add modified time to the data array if(!array_key_exists('modified',$data)){ $data['modified'] = date("Y-m-d H:i:s"); } if($checkResult->num_rows > 0){ // Prepare column and value format $colvalSet = ''; $i = 0; foreach($data as $key=>$val){ $pre = ($i > 0)?', ':''; $colvalSet .= $pre.$key."='".$this->db->real_escape_string($val)."'"; $i++; } $whereSql = " WHERE oauth_provider = '".$data['oauth_provider']."' AND oauth_uid = '".$data['oauth_uid']."'"; // Update user data in the database $query = "UPDATE ".$this->userTbl." SET ".$colvalSet.$whereSql; $update = $this->db->query($query); }else{ // Add created time to the data array if(!array_key_exists('created',$data)){ $data['created'] = date("Y-m-d H:i:s"); } // Prepare column and value format $columns = $values = ''; $i = 0; foreach($data as $key=>$val){ $pre = ($i > 0)?', ':''; $columns .= $pre.$key; $values .= $pre."'".$this->db->real_escape_string($val)."'"; $i++; } // Insert user data in the database $query = "INSERT INTO ".$this->userTbl." (".$columns.") VALUES (".$values.")"; $insert = $this->db->query($query); } // Get user data from the database $result = $this->db->query($checkQuery); $userData = $result->fetch_assoc(); } // Return user data return !empty($userData)?$userData:false; } } |
Site Settings and API Configuration (config.php)
the database settings and Facebook API configuration constant variables are defined in the config.php file.
Database Constants:
DB_HOST – Specify the database host.
DB_USERNAME – Specify the database username.
DB_PASSWORD – Specify the database password.
DB_NAME – Specify the database name.
DB_USER_TBL – Specify the table name where the user’s account data will be stored.
Facebook API Constants:
FB_APP_ID – Specify the Facebook App ID.
FB_APP_SECRET – Specify the Facebook App Secret.
FB_REDIRECT_URL – Specify the Callback URL.
Call Facebook API:
The PHP SDK library is used to connect with Facebook API and working with OAuth client.
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 |
<?php /* * Basic Site Settings and API Configuration */ // Database configuration define('DB_HOST', 'MySQL_Database_Host'); define('DB_USERNAME', 'MySQL_Database_Username'); define('DB_PASSWORD', 'MySQL_Database_Password'); define('DB_NAME', 'MySQL_Database_Name'); define('DB_USER_TBL', 'users'); // Facebook API configuration define('FB_APP_ID', 'Insert_Facebook_App_ID'); define('FB_APP_SECRET', 'Insert_Facebook_App_Secret'); define('FB_REDIRECT_URL', 'Callback_URL'); // Start session if(!session_id()){ session_start(); } // Include the autoloader provided in the SDK require_once __DIR__ . '/facebook-php-graph-sdk/autoload.php'; // Include required libraries use Facebook\Facebook; use Facebook\Exceptions\FacebookResponseException; use Facebook\Exceptions\FacebookSDKException; // Call Facebook API $fb = new Facebook(array( 'app_id' => FB_APP_ID, 'app_secret' => FB_APP_SECRET, 'default_graph_version' => 'v3.2', )); // Get redirect login 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; } |
Login & Get Facebook Account Data (index.php)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
{{urvanov-syntax-highlighter-internal:0}} <!DOCTYPE html> <html lang="en-US"> <head> <title>Login with Facebook using PHP by Developerguidance</title> <meta charset="utf-8"> </head> <body> <div class="container"> <div class="fb-box"> <!-- Display login button / Facebook profile information --> {{urvanov-syntax-highlighter-internal:1}} </div> </div> </body> </html> Logout (logout.php) If the user wishes to log out from their Facebook account, the logout.php file is loaded. Remove access token and user data from the SESSION. Redirect the user to the homepage. {{urvanov-syntax-highlighter-internal:2}} |
In this record, the Facebook API verification process is dealt with utilizing PHP.
- If the user authenticates with their Facebook account, the following happens:
- The profile information is retrieved from the Facebook account using Facebook Graph API.
- The account data is inserted into the database using checkUser() function of User class.
- The user’s account info is stored in the SESSION.
- The Facebook profile details (Name, First name, Last name, Email, Gender, Picture, and Profile link) is displayed on the webpage.
- Also, the Logout link is generated using getLogoutUrl() method of the login helper class.
Conclusion
In this tutorial, we’ve attempted to make Facebook Login execution speedier and easier. The model code incorporates Facebook Login with the Facebook SDK for PHP. You don’t have to add the SDK library documents independently, our source code contains every one of the necessary records with the SDK v5 for PHP. You just need to indicate some insignificant settings for adding login framework with Facebook to your site utilizing PHP.