Login System with Facebook using Php
In my previous post We learned about Login System with Google using Php and OAuth Api, Likewise this time we try Facebook. So in this tutorial I will explain how to make a Login System with Facebook using Php. User can login with their facebook details and access the website. So this process give permission to access basic information, profile, and their name with email will be stored in database if they are not stored before.
Like login with google we have to integrate our website to Facebook developers and get APP_ID and APP_SECRET.
Get APP_ID and APP_SECRET.
Step 1 – Go to the Url https://developers.facebook.com
login with you Facebook credentials and access the Facebook developer console.
Step 2 – Select MY APPS and ‘Add a New App’ for creating a new app.
Step 3 – Select website WWW for using website login integration
Step 4 – Create your Facebook app id and Choose your category, then skip all go to app setting.
Step 5 – Skip remain step and go to app setting. Its how your APP_ID and APP_SECRET. copy the code save it safely
Step 6 – Make sure check your app is active or not
Coding Step
Create database and table
CREATE TABLE IF NOT EXISTS `users` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(100) NOT NULL, `email` varchar(100) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;
Create config.php file for configuration with database.. Enter Your APP_ID and APP_SECRET and domain redirect your.
<?php error_reporting(E_ALL & ~E_DEPRECATED & ~E_NOTICE); ob_start(); session_start(); define('PROJECT_NAME', 'Login System with facebook using PHH - WWW.Developerdesks.com'); define('DB_DRIVER', 'mysql'); define('DB_SERVER', 'localhost'); define('DB_SERVER_USERNAME', 'root'); define('DB_SERVER_PASSWORD', ''); define('DB_DATABASE', 'login-facebook'); $dboptions = array( PDO::ATTR_PERSISTENT => FALSE, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8', ); try { $DB = new PDO(DB_DRIVER . ':host=' . DB_SERVER . ';dbname=' . DB_DATABASE, DB_SERVER_USERNAME, DB_SERVER_PASSWORD, $dboptions); } catch (Exception $ex) { echo $ex->getMessage(); die; } /* * ***** facebook related activities start ** */ require 'facebook_library/facebook.php'; define("APP_ID", "********"); /* Enter Your Facebook APP_ID */ define("APP_SECRET", "*************"); /* /* Enter Your Facebook APP_Secret */ /* make sure the url end with a trailing slash */ define("SITE_URL", "http://demos.developerdesks.com/login-with-facebook/"); /* this will be redirected after login */ define("REDIRECT_URL", SITE_URL."facebook_login.php"); /* Email permission for fetching emails. */ define("PERMISSIONS", "email"); /* If database connection is OK, then proceed with facebook * */ // create a facebook object $facebook = new Facebook(array('appId' => APP_ID, 'secret' => APP_SECRET)); $userID = $facebook->getUser(); // Login or logout url will be needed depending on current user login state. if ($userID) { $logoutURL = $facebook->getLogoutUrl(array('next' => SITE_URL . 'logout.php')); } else { $loginURL = $facebook->getLoginUrl(array('scope' => PERMISSIONS, 'redirect_uri' => REDIRECT_URL)); } ?>
Create redirect URL function facebook_login.php and this code for authentication the user with Facebook like we did previous in google verification. Check wether he gave correct credentials or not. if give correct credentials check it ans success page redirect to specified page and insert user data into database. If it returns error redirect back to index.php. If api returns user details check with database if user email exist and do the necessary accordingly and redirect back to home.php
<?php require_once './config.php'; // Only if user is logged in and given permission, we can fetch user details if ($userID) { try { if ($_SESSION["user_id"] == "") { // fetch user details. $user_profile = $facebook->api('/me'); // Now check if user exist with same email ID $sql = "SELECT COUNT(*) AS count from users where email = :email_id"; try { $stmt = $DB->prepare($sql); $stmt->bindValue(":email_id", $user_profile["email"]); $stmt->execute(); $result = $stmt->fetchAll(); if ($result[0]["count"] > 0) { // User Exist $_SESSION["name"] = $user_profile["name"]; $_SESSION["email"] = $user_profile["email"]; $_SESSION["new_user"] = "no"; } else { // New user, Insert in database $sql = "INSERT INTO `users` (`name`, `email`) VALUES " . "( :name, :email)"; $stmt = $DB->prepare($sql); $stmt->bindValue(":name", $user_profile["name"]); $stmt->bindValue(":email", $user_profile["email"]); $stmt->execute(); $result = $stmt->rowCount(); if ($result > 0) { $_SESSION["name"] = $user_profile["name"]; $_SESSION["email"] = $user_profile["email"]; $_SESSION["new_user"] = "yes"; } } } catch (Exception $ex) { #echo $ex->getMessage(); } header("location:home.php"); } $_SESSION["user_id"] = $userID; } catch (FacebookApiException $e) { $userID = NULL; } } else { // if not a authentic facebook user header("location:index.php"); } ?>
finally create link for login in index.php
<a href="<?php echo $loginURL; ?>"> Login with Facebook </a>
The last step as-usual Create Home.php page and logout.php code for the end process
<?php if ($_SESSION["new_user"] == "yes") { ?> <h2>welcome to developer desks.com </h2> <h2>Thank you for registering with us!!!</h2> <?php } else { ?> <h2>Welcome back <?php echo $_SESSION["name"] ?>!!!</h2> <?php } ?> <h5>Your Login email is: <?php echo $_SESSION["email"]; ?></h5>
<?php session_start(); $_SESSION = array(); unset($_SESSION); session_destroy(); header("location:index.php"); ?>
That’s it Enjoy the code.