Latest Posts
  • How to Advertise Your Vape Business on Social Media: A Complete Guide
  • How To Create Custom Module Form with Menu Link in Drupal
  • Some Common Mistakes to Avoid While Doing SEO for Shopify
  • iPhone 8 & iPhone X Features Prices and Specifications
  • Make Money Easily to Automatically Link Keywords with Affiliate Links in WordPress
  • Yoast SEO Premium License Key Cracked or Patched
  • 6 Reasons To Choose WordPress For Blogging
  • Most Popular Coding Language In 2018
  • Facebook
  • Twitter
  • Instagram
  • RSS
  • YouTube
Developer Desks Developer Desks
  • Home
  • Codes
    • WordPress
    • PHP
    • Jquery
    • Javascript
    • Guest
  • Demos
  • blog
  • Tech News
  • Submit Your Articles
  • Contact
Apis

Login System with Facebook using Php

October 20, 2015
Share on Facebook Share on Twitter Google+ Pinterest LinkedIn Tumblr Email
Login System with Facebook using Php

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.

Demo

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 Login System with Facebook using Php

Step 4 – Create your Facebook app id and Choose your category, then skip all go to app setting.

start ur websuitsLogin System with Facebook using Php

Login system with facebook using php

Step 5 – Skip remain step and go to app setting. Its how your APP_ID and APP_SECRET. copy the code save it safely

Login System with Facebook using Php

Step 6 – Make sure check your app is active or not

Login System with Facebook using Php

Login System with Facebook using Php

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.

Was this article helpful?

   

Awesome, share it:

Share Tweet Google Plus LinkedIn

Thanks!

Thanks for getting in touch with us.

Share this:

  • Twitter
  • Facebook
facebook loginlogin system
Raja sekar

I'm Rajasekar - Web developer, Freelancer, Blogger and Owner of DeveloperDesks. From India lives in Bahrain. I love to do coding, Creating websites and trying different with code and designs. You Can Hire Me

  • Website

Related Posts

Most Popular Coding Language in 2017

Most Popular Coding Language In 2018

February 18, 2017
How to Create Like & Unlike code like FB uisng PHP, MySQL and jQuery

How to Create Like & Unlike code like FB using PHP, MySQL and jQuery

November 25, 2016
live-search-in-php-and-mysql-using-jquery

Live search in PHP and Mysql using Jquery

October 13, 2016
  • Subscribe to our mailing list and get interesting stuff and updates to your email inbox.

    Thank you for subscribing.

    Something went wrong.

    we respect your privacy and take protecting it seriously

  • Help Me To Improve My Desk
    Buy Me A Coffee
  • About

    Developer Desks is Teach Coding and updates latest technology news in our blog. We have Highly professional web designer and Developer. We do Website developing work as a freelancer. Founded in 2015, This blog focus on the latest trends, tutorials, opinion articles as well as tips and tricks to empower our readers to become better web developers.

    Read More
    Facebook Twitter Instagram LinkedIn

    Copyrights © 2014 - 2022 Developer desks. All rights reserved. Designed by Developer desks.

  • Latest Posts
    • guest-blog-post
      How to Advertise Your Vape Business on Social Media: A Complete Guide
      Guest Blog May 30, 2018
    • How To Create Custom Module Form with Menu Link in Drupal
      Drupal April 4, 2018
    • Shopify Mistakes
      Some Common Mistakes to Avoid While Doing SEO for Shopify
      SEO September 18, 2017
    • iphone 8 features
      iPhone 8 & iPhone X Features Prices and Specifications
      Android updates September 13, 2017
  • Downloads
    Icon
    Multi select filter ajax 1750 downloads 3.43 KB
    Download
    Icon
    Export excel from mysql table data 338 downloads 3.55 KB
    Download
    Icon
    Check Existing username and match password using ajax 333 downloads 3.51 KB
    Download
    Icon
    php session without database 325 downloads 1.64 KB
    Download

Powered by Developer Desks.

Top
Developer Desks
     

    Loading Comments...