Facebook Login with PHP using facebook SDK

by  
Share:
facebook

Facebook needs no introduction. If you have a website where you have signup/registration section, Facebook login is a must. Not only it’s user-friendly,, it is quick and reliable as you will be having real user. In this tutorial we will see how to create a facebook application & integrate it in on your website.

Creating facebook application.

1. First thing first, Login to your facebook account here (All you guys have a master degree in this)

2. You need to create an application. Go to the developers apps page and then click on the Create new App button at the top right section.

Create new Facebook Application - 1

 

3. Enter your application name, select your category and then hit the continue button.

Create new Facebook Application - 2

4. If your are asked to enter security check to verify that you are human, please enter it and then hit the continue button.

Create new Facebook Application - 3

 

5. You will get your application ID and Application Secret Key. Give your Site Address, turn off sandbox mode and it’s done.

Create new Facebook Application - 4

 

Let’s Code Now

Let’s create a configuration file where we can define all application id, site url, access level and user login status credentials. I have named it configure.php. Attach the facebook php sdk with it. For full set of permission visit facebook developer site.

session_start();
require 'facebook_library/facebook.php';
define("APP_ID", "XXXXXXXXXXXXXXXXXXX");
define("APP_SECRET", "XXXXXXXXXXXXXXXXXXXX");
define("SITE_URL", "Your call back url");
// set the permissions and access level
define("PERMISSIONS", "email,user_hometown,user_about_me");

// 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 state.
if ($userID) {
  $logoutURL = $facebook->getLogoutUrl(array('next'=> SITE_URL.'logout.php'));
} else {
  $loginURL = $facebook->getLoginUrl( array('scope' => PERMISSIONS,'redirect_uri' => SITE_URL) );
}

// Only if user is logged in, we an fetch user details
if ($userID) {
  try {
	  $_SESSION["user_id"] = $userID;
    // fetch user details.
    $user_profile = $facebook->api('/me');
  } catch (FacebookApiException $e) {
	#debugResults($e);
    $userID = NULL;
  }

}

Create landing page for user who are not logged in. I have named it index.php
<?php
require_once("configure.php");
if (isset($_SESSION["user_id"]) && $_SESSION["user_id"] != "" ) {
	// user already logged in the site
	redirectURL(SITE_URL."home.php");
}
?>
<a href="<?php echo $loginURL; ?>" title="Login With Facebook" ><img src="facebook_login.png" width="209" height="40" border="0" alt="Facebook Login" /></a>

Create a home page for logged in user where we can display their information. I have named it home.php.
<?php
require_once("configure.php");
if (!isset($_SESSION["user_id"]) && $_SESSION["user_id"] == "" ) {
	// check if session expired
	redirectURL(SITE_URL);
}
?>
<!-- Logout Link -->
<a href="<?php echo $logoutURL; ?>"><img src="fb_logout.png" width="72" height="21" border="0" alt="Facebook Logout" /></a>   <br><br>

 <div class="resultRow">
        <strong>Name:</strong> <?php echo stripslashes($user_profile["name"]); ?>
    </div>
    <div class="resultRow">
        <strong>Profile Pic:</strong> <img src="https://graph.facebook.com/<?php echo $userID; ?>/picture">
    </div>
    <div class="resultRow">
        <strong>Gender:</strong> <?php echo stripslashes($user_profile["gender"]); ?>
    </div>
    <div class="resultRow">
        <strong>Email:</strong> <?php echo stripslashes($user_profile["email"]); ?>
    </div>
    <div class="resultRow">
        <strong>Profile Link:</strong> <a href="<?php echo stripslashes($user_profile["link"]); ?>" target="_blank"><?php echo stripslashes($user_profile["link"]); ?></a>
    </div>
    <div class="resultRow">
	    <strong>Hometown:</strong> <?php echo stripslashes($user_profile["hometown"]["name"]); ?>
    </div>
    <div class="resultRow">
        <strong>Bio:</strong> <?php echo stripslashes($user_profile["bio"]); ?>
    </div>
    <div class="resultRow">
        <strong>Quote:</strong> <?php echo stripslashes($user_profile["quotes"]); ?>
    </div>

If you want to see all your friends you can do so by making graph api call.
<?php
  try {
  // fetch user details.
     $user_friends = $facebook->api('/me/friends/');
      #debugResults($user_friends);	
  } catch (FacebookApiException $e) {
      #debugResults($e);
  }
?>

<div class="friendBox">
    <?php 
	if(count($user_friends["data"]) > 0 ) { 
		foreach($user_friends["data"] as $friends) {
	?>

	<div>
	<em><?php echo stripslashes($friends["name"]); ?></em><br>
    <img src="https://graph.facebook.com/<?php echo $friends["id"]; ?>/picture" height="50;">
    </div>

     <?php } }  ?>
    </div>

The last file will be the logout script. I have named in logout.php
<?php
require_once("configure.php");
$facebook->destroySession();
session_destroy();
redirectURL(SITE_URL);
exit;
?>

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

Vikash Kumar on

Excellent Post. Very helping. Keep up the good works.

Reply
Ajita John on

Thank you for this, it was indeed very helpful….do keep posting more !!!

Reply
Rajiv Shaw on

Just what I wanted. Thank you.

Reply
shivasurya on

fine super bro!i could easily understand ur tutorial! and it’s just like one click installation for websites!

Reply
Prathyusha Punni on

i got error is ” Given URL is not allowed by the Application configuration.: One or more
of the given URLs is not allowed by the App’s settings. It must match
the Website URL or Canvas URL, or the domain must be a subdomain of one
of the App’s domains. ” how can i solve this? and i did not saw sandbox mode on point number 5

Reply
Shahrukh Khan on

It’s because ur redirect URL in php code does not match with the app URL you gave in facebook developers site.

Reply
tharindu on

cant we access ofline web page

Reply
Shahrukh Khan on

Yes u can access it.. but u need the access tokens

Reply
bhathu on

thank u sir for wonderful guide…but iam stucking to get hometow and email i given permition and ll…please suggest

Reply
Shahrukh Khan on

u need user_hometown and friends_hometown permission and for email you need email permission from users.

Reply
Sunil on

Hey its a fantastic work,,,,
but m stucking with the
“Given URL is not allowed by the Application configuration.: One or more
of the given URLs is not allowed by the App’s settings. It must match
the Website URL or Canvas URL, or the domain must be a subdomain of one
of the App’s domains. ”

please help me in this by taking an example(mention an example url in php page and an example url in app development page).
and what is that uri url?

Reply
Shahrukh Khan on

Hi.. Make sure you give the right URL in the facebook app section. Also make sure the URL you give in facebook apps is the same when you run in the server.
E.g. if you give https://aarafacademy.com/php then you must run that project in php folder of the aarafacademy.com server.

Reply
Shahrukh Khan on

Thanks a lot. I really appreciate it.

Reply
swapnil on

hey buddy…can you help me with fetching user profile data from facebook..?

Reply
Shahrukh Khan on

What error are you getting.

Reply
cantonair on

After looking into a few of the blog articles on your web page, I really like
your technique of blogging. I added it to my bookmark site list and will
be checking back soon.

Reply
murali on

Hi bro

I used your code in below url,

http://www.jkfootwear.co.in/fb-with-friend/home.php

Its working 🙂 But failed to retrieve hometown and friends list. I tested even allowing my friends and home town list to public in FB,

Please reply ASAP how to fix this ?

Reply
Shahrukh Khan on

it must be a permission issue. also make sure you fetch it via graph api

Reply
murali on

permissions am using below one
(“PERMISSIONS”, “email,user_hometown,user_about_me,user_friends,user_birthday”);

but not retrieving friend list
and can i know about to fetch it via graph API?? Please try to reply ASAP.

Reply
balakumar on

Undefined index: gender in C:\wamp\www\fb_framework\home.php on line 45
Undefined index: email in C:\wamp\www\fb_framework\home.php on line 48

Undefined index: link in C:\wamp\www\fb_framework\home.php on line 51 Call Stack #TimeMemoryFunctionLocation 10.0017254464{main}( )..\home.php:0 ” target=”_blank”>

am getting lot of errors…pls help me bro

Reply
balakumar on

thanks bro….. how can i get frnd list in fb…pls help me bro…

Shahrukh Khan on

everything is mentioned in the article above please refer them. Also there are more article in the facebook category. please check them as well.

Akshay on

it is working fine in localhost but after host in server getUser() is always returning 0

Reply
Shahrukh Khan on

check you facebook application URL

Reply
pavan on

hi, its very good article, can i use the same thing using easy php ?

Reply
Shahrukh Khan on

Yes you can do that but make sure you follow the framework structure.

Reply
Nick on

Nice article,after going through it i just take a few minutest to create my facebook profile.Thanks for posting,keep it up!

Reply
Shahrukh Khan on

Thanks

Reply
Alisha on

The steps shared are very simple and easy to understand. It’s very helpful. Thank you.

Reply
Shahrukh Khan on

You are welcome.

Reply
muacanhosaigon.net on

Awesome! Its in fact amazing piece of writing, I
have got much clear idea about from this article.

Reply

Leave a Reply

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