Login System with Facebook with PHP and MySQL

by  
Share:
Login System with Facebook with php and mysql

In my last post I have posted login system with Google, this time it’s Facebook. Although I have posted quite a few post on login with facebook but it was not connected with database. So in this tutorial I will explain how to make a Login System with facebook using php and mysql. User will login with their facebook account, give permission to access basic profile, and their name with email will be stored in database if they are not stored before.

View Demo

Login with Facebook and creating facebook app for website.

I have already covered this topic before check Create facebook application and fetch friends with profile picture using php and fql. In that tutorial you will learn how to create a facebook application for website and fetch basic user details along with their friends list. In case if you are a newbie, I will recommend you to read that article before proceeding. Given below is the workflow of the login system with Facebook using PHP and MySQL.

Workflow of Login System with Facebook with php and mysqlLogin System with Facebook with php and mysql

Workflow of Login System with Facebook with php and mysqlLogin System with Facebook with php and mysql

Steps to create login system with php and mysql

Let’s code now. Create a database named “login_system” and create a table “users“.

CREATE DATABASE IF NOT EXISTS login_system;
USE login_system;
CREATE TABLE IF NOT EXISTS `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  `email` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;

I hope you have created a facebook app to get APP_ID and APP_SECRET. Set the config.php with all your site and facebook related credentials
// database connection
define('DB_DRIVER', 'mysql');
define('DB_SERVER', 'localhost');
define('DB_SERVER_USERNAME', 'root');
define('DB_SERVER_PASSWORD', '');
define('DB_DATABASE', 'login_system');

// site URL and facebook credentials
define("APP_ID", "your app id");
define("APP_SECRET", "your app secret");
/* make sure the url end with a trailing slash */
define("SITE_URL", "http://demos.aarafacademy.com/login-system-with-facebook/");
/* the page where you will be redirected after login */
define("REDIRECT_URL", SITE_URL."facebook_login.php");
/* Email permission for fetching emails. */
define("PERMISSIONS", "email");

// 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));
}

Set your index.php with the login URL in the anchor tag. So when the user clicks on it it will be redirected to facebook site.
<!-- Add login URL in index.php -->
<a class="btn btn-block btn-social btn-facebook" href="<?php echo $loginURL; ?>">Login with Facebook</a>

<!-- Add logout URL in home.php -->
<a class="btn btn-block btn-social btn-facebook" href="<?php echo $logoutURL; ?>">Logout</a>

User will login with their facebook accounts and give permission to the application. If user dont give permission then user will be redirected back to index page. If the user gives permission to the app then user information will be returned and data will be processed accordingly.
require_once './config.php';
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 facebook user not authentic
	header("location:index.php");
}

Just the final step to display user the message based on database transaction i.e. if user has registered for the first time or logged in back with their facebook account.
<?php if ($_SESSION["new_user"] == "yes") { ?>
    <h2>Thank you <?php echo $_SESSION["name"] ?>, for registering with us!!!</h2>
  <?php } else { ?>
    <h2>Welcome back <?php echo $_SESSION["name"] ?>!!!</h2>
<?php } ?>
<h5>Your email id is: <span style="text-decoration:underline;"><?php echo $_SESSION["email"]; ?></span></h5>

View Demo
Share to download the Source Codes for FREE!
We're glad to give free downloads, but we need your love to carry on making that.
Please support us by sharing the page.

Get the latest updates directly in your inbox for FREE: Subscribe here

Share your feedback / let me know your doubts regarding this tutorial in the comment box given below.

Share:
Hasan

Shahrukh Khan (Hasan)

A software engineer who's a die-hard coder, blogger, dreamer and mentor with years of expertise in web development. Know more...

Related Posts

Nadeem Ijaz on

Enjoyed the info you shared, Totally worth it reading, but don’t know how to config these downloaded files with my site’s files after editing.

Reply
Innocent Michael on

Hey i’m a newbie here.I want to create a website for myself and how to run it i don’t know. can i get a ny help? #thesoftwareguy

Reply
Shahrukh Khan on

what help do you need?

Er Imran Patel on

Hello Sir, i got a error on index.php page. undefined veritable ” loginURL “

Reply
rajveer singh on

you have not declared name in form for a input type assign the name.

Reply
Shahrukh Khan on

You have not set proper website URL in facebook developers apps page.

Reply
Psmusr on

Hello Shahrukh,

This tutorial is really helpful for us . I would like to see facebook login pop up window instead of redirecting the page to fb page . Plz add this tutorial in ur site .

Thanks ,
psmusr

Reply
kp on

at facebook_login.php, didnot get email id , i have return $user_profile with print_r
it will return
[id] => 933640156686991
[first_name] => Kannu
[gender] => female
[last_name] => Priya
[link] => https://www.facebook.com/app_scoped_user_id/933640156686991/
[locale] => en_US
[name] => Kannu Priya
[timezone] => 5.5
[updated_time] => 2015-02-05T15:56:50+0000
[verified] => 1

Reply
Shahrukh Khan on

Facebook is constantly changing their API and privacy policy, Kindly check their documentation for the latest support.

Reply
AFOM on

get email variable from session

$_SESSION[“email”]

Reply
bp on

kp can your fix?
if you can please tell me
thank you

Reply
intzar saifi on

hi sir,
i have a Fatal error: Uncaught exception ‘Exception’ with message ‘Facebook needs the CURL PHP extension.’ in base_facebook.php on line 19.
so how can solve this error easily ?

Reply
Shahrukh Khan on

check your php.ini file and see if your cURL is enabled or disabled.

Reply
Abhi Barua on

Hi , it’s a great tutorial but it seems you have made it with database, is it possible to create without databse like the below video,
I have found a video, check this and please let me know if it can be work,

Here
————————
https://www.youtube.com/watch?v=Va6wDtJIndI

Reply
Dedi Ananto on

// fetch user details
$user_profile = $facebook->api(‘/me’);

can’t get $user_profile[’email’], i can’t insert the value to my database

Reply
Mitja MIKLAV on

I have changed the line

$user = $facebook->api(‘/me’);

to

$user = $facebook->api(‘/me?locale=en_US&fields=first_name,last_name,email’);

so that i can get firstname, lastname & email.

It works, but everytime i logout (logout.php), it logout me of facebook to,
so when i want to login (facebook_login.php), i always need to login to facebook to.

Can you help me out? TNX

Reply
Shahrukh Khan on

that is because in the logout url I have added the facebook logout link too. just to make sure no one leave their facebook account open.
add this line in your main settings and check if this works
$logoutURL = $facebook->getLogoutUrl(array(‘next’ => SITE_URL . ‘logout.php’));

Reply
Mitja MIKLAV on

Tnx that helped 🙂

developer on

demo return email.but source not returning email 🙁

Reply
Shahrukh Khan on

what do you mean by this?

Reply
Mitja MIKLAV on

I had the same problem so i used this and it worked:

$user = $facebook->api(‘/me?locale=en_US&fields=email,first_name,last_name’);

I have declared the requested fields (email, first_name, last_name) and then the email was returned

I also use this in login url:

if ($userID) {
$logoutURL = BASE_URL.’logout.php’;
} else {
$loginURL = $facebook->getLoginUrl(array(‘scope’ => ’email’, ‘redirect_uri’ => FB_REDIRECT_URL));
}

I declare ‘scope’ => ’email’ and it worked as well, try one of this

Reply
godwin on

can u send tat changed code file to me… bcoz i am changing but not working…. show me the exact place to replace this two codes

Shahrukh Khan on

must be in the constant file or the main configuration file.

Junior on

Did not work here. I got a blank page with the url below:

Reply
Shahrukh Khan on

must be some coding problme what is the error message you are getting.

Reply
Yogesh Sharma on

I can’t get email id after login facebook .

Reply
Shahrukh Khan on

have you set the email permission.

Reply
godwin on

its perfectly login and logout.. but the problem is not displaying the name and mail id… i am doing it in localhost

Reply
Shahrukh Khan on

Maybe you are not able to hold the value in the variable properly. check it once more. maybe some minor issue if this thing is working.

Reply
Parmar Hardik on

Hello sir,

Database me entry nahi ho rahi he.

baki sab ache se chal raha he.

kya issue ho sakta he ?

please help me.

Reply
Shahrukh Khan on

please try to debug. or post the error message atleast.

Reply
Akshay on

Hi, I am not able to insert data through this code, coz of that data is not displaying on home page, can you please guide me, regarding this..

Reply
Shahrukh Khan on

what is your error message?

Reply
Akshay on

Hi, How can i set email permission?

Reply
Akshay on

Data is not inserted in my website data base, please help me regarding

Reply
Shahrukh Khan on

I have already email you the solution, your database code insert code is not correct.

wendellprincipe@yahoo.com on

hi,

got this error.

Not Found

The requested URL /login-system-with-facebook/facebook_login.php was not found on this server.

Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.

Reply
wendellprincipe@yahoo.com on

not saving database.. 🙁

Reply
Stanley on

Thanks for the tutorial. i have a slight problem though…It successfully logs in but it doesn’t populate the database with any data.

i have reviewed the SQL queries a lot of times, but it’s still not working.

Reply
Shahrukh Khan on

what is the error?

Reply
priyanka on

can u tell us how to get logged user friend list..only friends name in php
thanks in advance

Reply
Shahrukh Khan on

you need to call graph api like me/friends

Reply
Kousalya on

i could able to login successfully ,but data is not stored in database
can u tell me where is the problem

Reply
Shahrukh Khan on

whats the error you are getting

Reply
Anna on

Hi Shahrukh Khan,
How can I get more informations like user historic??please any help

Reply
Shahrukh Khan on

You need to check the facebook developers API

Reply
shubro on

thanks for this tutorials!!but i am unable save data in database.please help me

Reply
Shahrukh Khan on

whats your issue.

Reply
Shekar on

im facing this error

can u help me ?

Can’t Load URL: The domain of this URL isn’t included in the app’s domains. To be able to load this URL, add all domains and subdomains of your app to the App Domains field in your app settings.

Reply
nav on

Its returning index.php#_=_

No login details are returning . may i know what is the prblm

Reply
Shahrukh Khan on

kindly check your error console or debug cant say with assumption

Reply
raj on

its redirecting again to index page intead ofhome pageno error thrown

Reply
Shahrukh Khan on

check the session variable

Reply
Anish on

hey can i ask u a question i had made a website for book shop,, o am having problem in the admin side are if i need to delete a book from category its not deleting can u help me out plz

Reply
Shahrukh Khan on

what error are you getting?

Reply
happi on

Thanks for the tutorial but i’m unable to save to database
Here is my code
require(“libs/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:profile.php”);
}
$_SESSION[“user_id”] = $userID;
} catch (FacebookApiException $e) {
$userID = NULL;
}
} else {
// if not a authentic facebook user
header(“location:register.php”);
}

Reply
Shahrukh Khan on

please debug, see if you are able to fetch the value first.

Reply
Kostas on

Hello,

Thanks for the instructions.
I tried to use them in my site but I have a problem. I press ‘Login with Facebook’, I submit my facebook credentials and after it returns me to index.php page without any error plus no data in mysql database.

Any ideas whats wrong.

Thanks

Reply
Shahrukh Khan on

cant say much about it. debug the data and see what is data returning,

Reply
Software services on

Good blog you have here.. It’s difficult to find quality writing like yours
these days. I honestly appreciate people like you!
Take care!!

Reply
Innocent Michael on

i want to have more of software knowledge. but, i need help

Reply

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.