How to Login with Facebook using facebook-php-sdk and MySQL?

Today now in this post, I am going to share with you an example of how we can integrate the login with facebook in PHP website by using Facebook Graph API.

Some website normally need registration form for the sign up, But the users are not interested to filling any big registration forms. So we can easily implement the login or register with the facebook login, users don’t need to fill big form. Now in this tutorial i will help to implement login with the facebook in your PHP project.

Now In this post i will show you step by step , i will give you an example of sign in with facebook account from the scratch. In this example facebook account details will get and store it on our MySQL database.

Step 1: Create Facebook App

Now in this step, we need to create a new facebook app for access the other user details, So at first create our own facebook app By the following link, here give all the screen shot. so just follow the bellow screen shot.

Go On Facebook Developer account : https://developers.facebook.com/apps.

Screenshot : 1

Then Next Click on “Add a New App”

Screenshot : 2

Add the Facebook App name and category.

creenshot : 3

Then Now Click on “Setting” Link On Sidebar.

Screenshot : 4

Now, you need to add the platform. You can add the platform as like as bellow screenhot. choose “Website” and Add our site URL(For This example add : http://localhost:8000).

After the added platform, we can get App Id and secret from here:

Step 2: Download Facebook Graph API

Now in this step, we need to download the facebook-php-sdk from git. So, click here and then download api : facebook-php-sdk.

After the download Just we need to copy “src” folder and put it on our project root path, and then rename it to “api”.

Step 3: Create Database Table

Then now in this step, we need to create the database with “users” table for store the facebook details on that table. So we can create the table by following SQL Query:

Create Users Table

CREATE TABLE `users` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `facebook_id` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
    `first_name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
    `last_name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
    `email` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
    `gender` varchar(10) COLLATE utf8_unicode_ci NOT NULL,
    `picture` text  COLLATE utf8_unicode_ci NOT NULL,
    PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Step 4: Add PHP files

In this step we need to add the four PHP files, as like bellow:

1. config.php : In this file, we need to add the facebook app id and secret.

2. index.php : In this file, we need to add layout file and manage if login then the different layout and different for the logout user.

3. storeData.php : In this file, we write the database logic, We will also insert and check user data from this file.

4. logout.php : At last In this file, we destroy the session for logout user.

config.php

<?php
 require 'api/facebook.php';
 $config['App_ID'] = 'Facebook App Id';
 $config['App_Secret'] = 'Facebook App Secret';
 $facebook = new Facebook(array(
  'appId'  => $config['App_ID'],
  'secret' => $config['App_Secret']
 ));


?>

index.php

<?php


 require 'config.php';
 require 'storeData.php';


 $user = $facebook->getUser();


?>


<html>
<head>
	<title>Login With Facebook</title>
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>


<div class="container" style="margin-top:20px;">
	<h2 class="text-center" >CodingsPoint.com</h2>


	<?php if($user){ ?>


		<?php
			$userProfile = $facebook->api('/me?fields=id,first_name,last_name,email,gender,locale,picture');


			$userClass = new User;
			$userData = $userClass->checkFBUserData($userProfile);
		?>


		<?php if(!empty($userData)){ ?>
		        <h3>Facebook User Details</h3>
			<img src="<?php echo $userData['picture']; ?>">
	      	        <p><strong>Fabebook ID:</strong> <?php echo $userData['facebook_id'] ?> </p>
	      	        <p><strong>First Name:</strong> <?php echo $userData['first_name'] ?> </p>
                        <p><strong>Last Name:</strong> <?php echo $userData['last_name'] ?> </p>
	      	        <p><strong>Email:</strong> <?php echo $userData['email'] ?> </p>
	      	        <p><strong>Gender:</strong> <?php echo $userData['gender'] ?> </p>
	      	        <a href="logout.php?logout">Facebook Logout</a>
      	       <?php }else{ ?>
      		 <p>Something is wrong.</p>
      	       <?php } ?>


	<?php }else{ ?>


		<?php
			$loginUrl = $facebook->getLoginUrl(['scope'=>'email']);
		?>


		<div id="loginbox" style="margin-top:20px;" class="mainbox col-md-6 col-md-offset-3 col-sm-8 col-sm-offset-2">                    
                  <div class="panel panel-info" >
                    <div class="panel-heading">
                        <div class="panel-title">Sign In</div>
                        <div style="float:right; font-size: 80%; position: relative; top:-10px"><a href="#">Forgot password?</a></div>
                    </div>     


                    <div style="padding-top:30px" class="panel-body" >


                        <div style="display:none" id="login-alert" class="alert alert-danger col-sm-12"></div>

                            
                        <form id="loginform" class="form-horizontal" role="form">

                                    
                            <div style="margin-bottom: 25px" class="input-group">
                                <span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
                                <input id="login-username" type="text" class="form-control" name="username" value="" placeholder="username or email">                                        
                            </div>

                                
                            <div style="margin-bottom: 25px" class="input-group">
                                <span class="input-group-addon"><i class="glyphicon glyphicon-lock"></i></span>
                                <input id="login-password" type="password" class="form-control" name="password" placeholder="password">
                            </div>

                                
                            <div class="input-group">
                              <div class="checkbox">
                                <label>
                                  <input id="login-remember" type="checkbox" name="remember" value="1"> Remember me
                                </label>
                              </div>
                            </div>


                            <div style="margin-top:10px" class="form-group">
                                <div class="col-sm-12 controls">
                                  <a id="btn-login" href="#" class="btn btn-success">Login  </a>
                                  <a id="btn-fblogin" href="<?php echo $loginUrl; ?>" class="btn btn-primary">Login with Facebook</a>
                                </div>
                            </div>


                            <div class="form-group">
                                <div class="col-md-12 control">
                                    <div style="border-top: 1px solid#888; padding-top:15px; font-size:85%" >
                                        Don't have an account! 
                                    <a href="#">Sign Up Here</a>
                                    </div>
                                </div>
                            </div>


                            </form>


                        </div>                     
                    </div>  
        </div>


	<?php } ?>


</div>


</body>
</html>

storeData.php

<?php


class User {
	public $table_name = 'users';


	function __construct(){
		/* database configuration */
		$dbServer = 'localhost';
		$dbUsername = 'root';
		$dbPassword = 'root';
		$dbName = 'h_test';


		/* connect database */
		$con = mysqli_connect($dbServer,$dbUsername,$dbPassword,$dbName);
		if(mysqli_connect_errno()){
			die("Failed to connect with MySQL: ".mysqli_connect_error());
		}else{
			$this->connection = $con;
		}
	}


	function checkFBUserData($user){
		$prev_query = mysqli_query($this->connection,"SELECT * FROM ".$this->table_name." WHERE facebook_id = '".$user['id']."'") or die(mysql_error($this->connection));
		if(mysqli_num_rows($prev_query)>0){
			$update = mysqli_query($this->connection,"UPDATE $this->table_name SET facebook_id = '".$user['id']."', first_name = '".$user['first_name']."', last_name = '".$user['last_name']."', email = '".$user['email']."', gender = '".$user['gender']."', picture = '".$user['picture']['data']['url']."' WHERE facebook_id = '".$user['id']."'");
		}else{
			$insert = mysqli_query($this->connection,"INSERT INTO $this->table_name SET facebook_id = '".$user['id']."', first_name = '".$user['first_name']."', last_name = '".$user['last_name']."', email = '".$user['email']."', gender = '".$user['gender']."', picture = '".$user['picture']['data']['url']."'");
		}

		
		$query = mysqli_query($this->connection,"SELECT * FROM $this->table_name WHERE facebook_id = '".$user['id']."'");
		$result = mysqli_fetch_array($query);
		return $result;
	}
}
?>

logout.php

<?php


 require 'config.php';


 $facebook->destroySession();
 session_start();
 unset($_SESSION['userdata']);
 session_destroy();
 header("Location:index.php");


?>

Step 5: Run Example

We can quick run our example by the following command, so run the bellow command for run PHP project.

php -S localhost:8000

Now, we can check from our url by bellow URL:

http://localhost:8000

Read Also: How to implement infinite ajax scroll pagination in Laravel?

Thanks for read. I hope it help you. For more you can follow us on facebook

close

About Shahriar Sagor

My name is Shahriar sagor. I'm a developer. I live in Bangladesh and I love to write tutorials and tips that will help to other Developer's. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.

View all posts by Shahriar Sagor →