Login with Facebook using PHP MySQL Example

By Hardik Savani November 5, 2023 Category : PHP Bootstrap MySql

Hey Guys,

This extensive guide will teach you login with facebook php mysql. We will use facebook login php sdk example. If you have a question about php authentication facebook tutorial then I will give a simple example with a solution. In this article, we will implement a sign in with facebook php code download. Alright, let’s dive into the details.

In this post, I am going to share with you How to integrate login with facebook in PHP website using Facebook Graph API.

In Website normally registration form for sign up, But users are not interested to filling the big registration forms. So you can implement login or register with facebook login, users don't require to fill big form. This tutorial will help to implement login with facebook in your PHP project.

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

After follow all step, you will find preview like as bellow preview, you can also download script and check demo:

Preview:

Step 1: Create Facebook App

In this step, we have to create new facebook app for access other user details, So first create your own facebook app By following link, here give all screen shot so follow bellow screen shot.

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

Screenshot : 1

Next Click on "Add a New App"

Screenshot : 2

Now Add Facebook App name and category.

Screenshot : 3

Now Click "Setting" Link On Sidebar.

Screenshot : 4

Now, you have to add platform. You can add platform like as bellow screenhot. choose "Website" and Add your site URL(For This example add : http://localhost:8000).

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

Step 2: Download Facebook Graph API

In this step, we have to download facebook-php-sdk from git. So, click here and download api : facebook-php-sdk.

After download Just copy "src" folder and put it on your project root path, and rename it to "api".

Step 3: Create Database Table

In this step, we have to create database with "users" table for store facebook details on that table, so you can create 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 have to add four PHP files, as like bellow:

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

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

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

4. logout.php : In this file, we destroy 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" >ItSolutionStuff.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

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

php -S localhost:8000

Now, you can check from your url by bellow URL:

http://localhost:8000

I hope it can help you...

Shares