Login with Facebook in Your Website Using Facbook SDK for PHP

Hello friends we have already learnt how easily you can implement login with Google plus in your website using Open Auth. Today we will learn another easy way to implement Facebook login in your website using Facebook SDK for PHP. Facebook SDK for PHP helps developers connect with graph api and leverage Facebook login in their websites. We will start from basics so if you don’t know anything about creating Facebook app and using it, don’t worry you are going to learn it today. In order to access Graph API you need to have a Facebook application created and you must make that application live i.e. available to public. So let’s see how to create Facebook application to get your client id and client secret.

facebook login php

Live Demo         Download

Steps to Create Facebook Application:

1> Go to https://developers.facebook.com/  on the top menu go to apps and then create a new app.

create fb app

2> Go to settings and set your site URL and mobile site URL. You also need to fill app domain i.e. domain where your app files will be hosted.

Facebook App setting

3> Now go to advanced setting and set redirect URL path. This is the path of login.php file that you will download in demo.

redirect uri

4> In the last step you have to make your app live so that it can be accessed by public. To do this go to status and review tab and you will see an option to make your app public.

live fb app

Note: If you are trying to implement this in your local server then I suggest you not to use IP (e.g. 127.0.0.1) in url. Direct your IP to localhost or test.com (any domain name) something like that from your DNS setting in host file.

Now I assume you have created your Facebook App and it’s time to use it to create our script for Facebook Login. First you will have to download Facebook SDK for PHP (It’s included in demo). Now we need to do two things, display user a login button and then authenticate user if he enters correct credentials. Below is our code for displaying a login button and opening a pop up so that user can enter his Facebook Credential without navigating from main page:

</p>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Login with Facebook using SDK for PHP - InfoTuts</title>
 <link rel="stylesheet" type="text/css" media="all" href="style.css">
</head>
<body>
<div id="mhead"> <h2>Login with Facebook - InfoTuts </h2></div>
<div id="fblogin" onclick="applogin(); "><img src="InfoTuts-facebook-login.png" alt="Login with Facebook" /></div>
</body>
</html>
<script>

function applogin(){
 var w_left = (screen.width/4);
 var w_top = (screen.height/4);
window.open('<?php echo $url; ?>','targetWindow','toolbar=no,titlebar=no,location=no,status=no,menubar=no,scrollbars=no,resizable=no,width=900,height=500,top='+w_top+',left='+w_left+'');
 }
 </script>
<p style="text-align: justify;">

Then we have to authenticate user and after authentication we will display few information from his profile and provide him an option to logout from our application. Below is the code for the same:

</p>
<?php @session_start();
$code=$_GET['code'];
if(isset($code) && $code!=''){
class F_login {

function include_lib() {
 @session_start();
require 'lib/src/facebook.php';
 }

 function login(){
 $code=$_GET['code'];
 $ur="http://infotuts.com/demo/facebook-login-php/login.php?code=".$code;  // change url
 echo "<script>window.close(); window.opener.location.href='".$ur."';</script>";
 header('P3P: CP="NOI ADM DEV COM NAV OUR STP"');
 $this->include_lib();
 $facebook = new Facebook(array(
 'appId' => 'xxxxxxxxxxxxxxxxx',  // your app id
 'secret' => 'xxxxxxxxxxxxxxxxxxxxxxxxx', // your app secret
 'cookie' => true
 ));
 $user = $facebook->getUser();
 if ($user) {
 try {
 $user_profile = $facebook->api('/me');
 } catch (FacebookApiException $e) {
 error_log($e);
 $user = null;
 }
 $logoutUrl = $facebook->getLogoutUrl();
 $user_fbid = $fbuser;
 $user_email = $user_profile["email"];
 $user_name = $user_profile["first_name"];
 $user_image = "https://graph.facebook.com/".$user."/picture?type=large";
 ?>
 <!DOCTYPE html>
<html>
<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Login with Facebook using SDK for PHP - InfoTuts</title>
 <link rel="stylesheet" type="text/css" media="all" href="style.css">
</head>
<div id="userinfo">
<table class="usertable">
<tr>
 <td>Your Name: </td>
 <td><b><?php echo $user_name; ?></b></td>

</tr>
<tr>
 <td> Your Email</td>
 <td><?php echo $user_email; ?></span></td>
</tr>
<tr>
 <td>Your Profile Pic: </td>
 <td valign="top" rowspan="2"><img src="<?php echo $user_image; ?>" height="100"/></td>

</tr>
<tr><a onClick="FBLogout();" href="<?php echo $logoutUrl; ?>">Logout</a></tr>
</table>
</div>

</body>

</html>

 <?php
 }

 } // end function
}

$obj= New F_login();
$obj->login();

}else{
header('P3P: CP="NOI ADM DEV COM NAV OUR STP"');
require 'lib/src/facebook.php';
 $facebook = new Facebook(array(
 'appId' => 'xxxxxxxxxxxx', // your app ID
 'secret' => 'xxxxxxxxxxxxxxxxxxxxxxxxxx' // your app secret
 ));
 $user = $facebook->getUser();
 //$statusUrl = $facebook->getLoginStatusUrl();
 $url = $facebook->getLoginUrl(array('scope' => 'email,offline_access,publish_stream',
 'cookie' => true,
 'redirect_uri'=>'http://infotuts.com/demo/facebook-login-php/login.php')); // enter redirect uri
 $logoutUrl = $facebook->getLogoutUrl();
?>
<p style="text-align: justify;">

Note:  You need to replace client ID, client secret and redirect URL with your client ID and client secret and redirect URL respectively. Its commented on Download file where to change.

This is really easy and simple to integrate in your web application. You can also write little bit more code to store users information in your database so that you can know who all are returning visitors and also you will create an email list of all users.  I have left homework for you as this script can be enhanced in terms of variable use and flexibility 😉 Let me know if you have any questions in your mind. We will be covering Login with Twitter soon. Please share this simple but powerful tutorial with your friends and followers.

About sanjeev

sanjeev
Dreamer, Blogger and Thinker. I love to help people in solving their problems. You can also join me HERE

Related posts:

5 Responses so far.

  1. I have subscribed but unable to download the tutorial. It’s been more than 24 hours already and I activated the subscription through feedburner.

    It would also be nice if you give file structure and explicit tutorial. This tutorial assumes you are an expert.

    I got this message when i tried to subscribe again
    “shamsideenquadri@yahoo.com is already subscribed to the mailing list of InfoTuts”

  2. hi, thanks for the code, but i am getting a message when the facebook sign in page openssaying..
    You are using a display type of ‘page’ in a small browser window or popup. For a better user experience, show this dialog with our JavaScript SDK without specifying an explicit display type. The SDK will choose the best display type for each environment. Alternatively, use display type ‘popup’ if you have special requirements precluding you from using the SDK. This message is only visible to developers of your application.

    can u plz tell me how it can be done

  3. hello sir this tutorial is very helpfull
    but sir i want to login with facebook using codeigniter
    so if you have any solution please help

  4. Hi , it’s a great tutorial but it seems you have made it with database, is it possible to create with databse like the below video.

    I have found a video, check this and please let me know if it can be work.

Comments are closed.