Login with Facebook using PHP


Nowadays users are not interested in filling a big form to registration. Short registration process helps to get more subscribers for your website. Login with Facebook is a quick and powerful way to integrate registration and login system on the website. Facebook is a most popular social network and most of the users have a Facebook account. Facebook Login allow users to sign into your website using their Facebook account credentials without sign up on your website.

This tutorial will explain how you can implement user login and registration system with Facebook using PHP and store the user profile data into the MySQL database. We will use Facebook PHP SDK with Facebook Graph API to build Facebook Login system with PHP and MySQL.

Before you begin to integrate Login with Facebook using PHP, take a look at the folders and files structure.

  • inc/
    • base_facebook.php
    • facebook.php
  • User.php
  • fbConfig.php
  • index.php
  • logout.php
  • images/
    • fblogin-btn.png

Facebook Apps Creation

To access Facebook API you need to create Facebook App and specify App ID & App Secret at the time of call Facebook API. Follow the step-by-step guide to creating and configure a Facebook App from the App Dashboard.

  • Go to the Facebook App Dashboard and log in with your Facebook account.
  • Create a new Facebook apps with your desired name (like WebLogin).
  • If you want to test Facebook login at the localhost server, then your App Domains should be localhost. Also, localhost domain will only work, once you add platform. For add a platform click on Settings link from the left side menu panel » Click on the Add Platform button » Choose Website category » Enter site URL (http://localhost/facebook_login_with_php/).
  • Once you completed the above steps, your apps settings page would something like the below.
    codexworld-facebook-apps-creation
  • Now click on Status & Review link from the left side menu panel and make your apps live. Contact email is required for enable the apps live option. If you have not added apps contact email earlier, go to the settings page and add email. Once you submit the contact email, you would be able to enable the apps live option.
  • Congratulation! your apps creation has completed.

Are you want to get a detailed guide on Facebook App creation? Go through this guide to creating a Facebook App and get App ID & App Secret.

Database Table Creation

To store the user information from the Facebook database, a table (users) need to be created in MySQL database (codexworld). At first, create a database (like codexworld) and run the below SQL on the database. The following SQL creates a users table to the database for inserting user profile information.

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(5) COLLATE utf8_unicode_ci NOT NULL,
 `locale` varchar(10) COLLATE utf8_unicode_ci NOT 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;

User Class (User.php)

The User class helps to insert or update user data to the database using PHP and MySQL. In User.php file, you only need to specify your MySQL database credentials ($dbHost, $dbUsername, $dbPassword, and $dbName) and table name ($userTbl) where you want to store the user data.

<?php
class User {
    private 
$dbHost     "localhost";
    private 
$dbUsername "root";
    private 
$dbPassword "";
    private 
$dbName     "codexworld";
    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']."', picture = '".$userData['picture']."', link = '".$userData['link']."', modified = '".date("Y-m-d H:i:s")."' 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']."', first_name = '".$userData['first_name']."', last_name = '".$userData['last_name']."', email = '".$userData['email']."', gender = '".$userData['gender']."', locale = '".$userData['locale']."', picture = '".$userData['picture']."', link = '".$userData['link']."', created = '".date("Y-m-d H:i:s")."', modified = '".date("Y-m-d H:i:s")."'";
                
$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;
    }
}
?>

Facebook API Configuration (fbConfig.php)

In fbConfig.php file, define Facebook App ID ($appId), App Secret ($appSecret), Callback URL ($redirectURL), and Permissions ($fbPermissions).

<?php
session_start
();

//Include Facebook SDK
require_once 'inc/facebook.php';

/*
 * Configuration and setup FB API
 */
$appId 'InsertAppID'//Facebook App ID
$appSecret 'InsertAppSecret'// Facebook App Secret
$redirectURL 'http://localhost/facebook_login_with_php/'// Callback URL
$fbPermissions 'email';  //Required facebook permissions

//Call Facebook API
$facebook = new Facebook(array(
  
'appId'  => $appId,
  
'secret' => $appSecret
));
$fbUser $facebook->getUser();
?>

Note that: You’ll find the App ID and App Secret on your Facebook Apps settings page.

Login & Profile Information (index.php)

If the user already logged in with Facebook account, the profile details would be displayed, otherwise, Facebook login button would appear.

<?php
//Include FB config file && User class
require_once 'fbConfig.php';
require_once 
'User.php';

if(!
$fbUser){
    
$fbUser NULL;
    
$loginURL $facebook->getLoginUrl(array('redirect_uri'=>$redirectURL,'scope'=>$fbPermissions));
    
$output '<a href="'.$loginURL.'"><img src="images/fblogin-btn.png"></a>';     
}else{
    
//Get user profile data from facebook
    
$fbUserProfile $facebook->api('/me?fields=id,first_name,last_name,email,link,gender,locale,picture');
    
    
//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'],
        
'picture'         => $fbUserProfile['picture']['data']['url'],
        
'link'             => $fbUserProfile['link']
    );
    
$userData $user->checkUser($fbUserData);
    
    
//Put user data into session
    
$_SESSION['userData'] = $userData;
    
    
//Render facebook profile data
    
if(!empty($userData)){
        
$output '<h1>Facebook Profile Details </h1>';
        
$output .= '<img src="'.$userData['picture'].'">';
        
$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/><a href="'.$userData['link'].'" target="_blank">Click to Visit Facebook Page</a>';
        
$output .= '<br/>Logout from <a href="logout.php">Facebook</a>'
    }else{
        
$output '<h3 style="color:red">Some problem occurred, please try again.</h3>';
    }
}
?> <div><?php echo $output?></div>

Logout (logout.php)

When the user wishes to logout from their account, logout.php file is called.

<?php
//Include FB config file
require_once 'fbConfig.php';

//Unset user data from session
unset($_SESSION['userData']);

//Destroy session data
$facebook->destroySession();

//Redirect to homepage
header("Location:index.php");
?>

If you want to remove app permission on logout, place the following code after including the fbConfig.php file. App Permission screen will appear every time when the user tries to login in with Facebook.

//Remove App permissions
$fbUid $_SESSION['userData']['oauth_uid'];
$facebook->api('/'.$fbUid.'/permissions','DELETE');

Conclusion

In this tutorial, we’ve tried to make Facebook Login implementation quicker and easier. Using our script, you only need to include 2 API files (base_facebook.php and facebook.php) to integrate Login with Facebook in your website. If you have any query or suggestions about this tutorial and scripts, feel free to comment here.

121 Comments

  1. Sastro Jahat Said...
  2. Priyanka Said...
  3. Stanley Said...
    • CodexWorld Said...
  4. Rahul Said...
  5. Satish Said...
  6. Satish Said...
  7. Rezz Said...
  8. Rommel Evangelista Said...
  9. Addrk Said...
  10. Jason Said...
  11. Manish Saraswat Said...
  12. Sai Said...
  13. Hemraj Said...
  14. Vilas Galave Said...
1 3 4 5

Leave a reply

Connect With CodexWorld