Facebook Signin using the PHP SDK

Have you setup a facebook app and downloaded their sdk, and don\'t know where to go from there?

Facebook authentication using PHP

This guide applies to the facebook PHP SDK version 3.0.

Having facebook authenticate your users may benefit you in such a way that they won\'t have to go through yet another registration process with required fields, captchas email verification and such.

This article assumes you have already prepared your project by:

  • A facebook app is correctly setup at developers.facebook.com
  • You\'ve downloaded and extracted their PHP SDK at github
  • You have your facebook appId available.
  • You have your facebook app secret available.

Creating the Facebook Object

The first step is of course to include the facebook sdk in your .php file in a similar manner:

require_once(\'facebookapi/facebook.php\');
Remember to change the path to facebook.php to match your code setup.

Once the sdk is included you can safely create an instance of the Facebook object in a very straightforward way:

$facebook = new Facebook(array(
  \'appId\'  => \'FACEBOOK_APPID\',
  \'secret\' => \'FACEBOOK_SECRET\',
  \'domain\'=>\'YOUR_DOMAIN\',
  \'cookie\' => true,
  \'fileUpload\' => false
));

The three values written in capital letters must reflect the values at https://developers.facebook.com/apps , or your app won\'t work.

  • FACEBOOK_APPID is marked with (1) in the screenshot.
  • FACEBOOK_SECRET is marked with (2).
  • YOUR_DOMAIN is marked as (3).

Get Authenticated with Facebook

So you have the facebook object ready, now let\'s get authenticated. The first thing we need to do is to redirect your users to a facebook login screen, the url which to redirect the users to is fetched from the facebook object.

$loginparams = array(
  \'scope\' => \'publish_stream, user_birthday\',
  \'redirect_uri\' => \"THE_URL_TO_THE_CURRENT_FILE?fblogin=y\",
  \'fbconnect\' => 1,
  \'canvas\' => 0
  
);
$facebook_loginUrl = $facebook->getLoginUrl($loginparams);

The $loginparams variable tells which permissions your app should request, and which url to redirect to after authenticating the user. In this example we have this code in a file that is included in all pages on the site to make sure the facebook code is executed no matter which page is requested.

But wait, what\'s with the \"?fblogin=y\" appended at the end of the redirect url?
- Due to a bug in the facebook php sdk, the first time your page is loaded after a successful authentication you won\'t detect that the user in fact is logged in. Read more about this here. Don\'t worry, we will take care of it later.

So we have the facebook instance, and the login url, let\'s check if the user is authenticated with facebook.

$user = $facebook->getUser();
if ($user)
{
 // user is signed in, do whatever you wish.
}
else
{
 header(\'Location: \'.$facebook_loginUrl);
 // This is just an example, don\'t do it this way as
 // it may put your user in a loop when sign in fails.
 //  A better  approach for production code would be 
 // to prepare a login button that redirects to the 
 // $facebook_loginUrl when pressed.
}

Let\'s deal with the bug

Remember the \"?fblogin=y\" querystring appended to the redirect_url?
-Check if that value exists in the current querystring and redirect to the same url, but without the fblogin query string. This will be practically the same as reloading the page.

if ((isset($_GET[\'fblogin\'])) && ($_GET[\'fblogin\'] == \'y\'))
{
 $url = str_replace(\'fblogin=y&\', \'\', getCurrentUrl());
 header(\'Location: \'.$url);   
}

One important thing to remember when implementing your code the same way as described here, as we make use of the php header() function all code in this example MUST be executed before any output at all is sent to the browser.

Oh, having trouble with the call to getCurrentUrl()?
- That\'s just a minor utility function. If you don\'t know how to get the current url, here it is:

function getCurrentUrl()
{
	 $pageURL = \'http\';
	 if ($_SERVER[\"HTTPS\"] == \"on\") {$pageURL .= \"s\";}
	 $pageURL .= \"://\";
	 if ($_SERVER[\"SERVER_PORT\"] != \"80\") {
	  $pageURL .= $_SERVER[\"SERVER_NAME\"].\":\".
                      $_SERVER[\"SERVER_PORT\"].
                      $_SERVER[\"REQUEST_URI\"];
	 } else {
	  $pageURL .= $_SERVER[\"SERVER_NAME\"].$_SERVER[\"REQUEST_URI\"];
	 }
	 return $pageURL;   
}
 

Live example

You can try a live example at InstaPoller.com. Instapoller was developed by us on behalf of a client.

If you enjoyed this article, please share and comment! Thank you.

 Facebook Signin using the PHP SDK

Have you setup a facebook app and downloaded their sdk, and don\'t know where to go from there?

 Facebook PHP SDK login problem

Have you integrated a facebook login to your site, or are you planning to? There\'s a small bug involving the sign in process that can make your life miserable unless you know how to get around it. Here\'s one possible solution.

 Internet Explorer 9, JScript Error c00c023f

Ajax and Error c00c023f

After updating to Internet Explorer 9, a previously working ajax driven site of mine stopped working sporadically.

In this short article you will see how to reproduce, and how to solve the problem.

 Facebook Like button shows blank, solution

The \"EnkelAdress on Facebook\" button displayed just fine for a couple of days and then suddenly it showed up blank, no matter how many times trying to copy the code provided by Facebook. After quite some time digging deep in the information jungle we found the solution.

Page 1 / 2

 Thumbs Up Immerse VR Headset

This Immerse headset from ThumbsUp offers both positive and negative sides.

 Know your limits: Web Design

You might have the best app ever created, or you might have the user friendliest web page in the world. You might even have the most useful piece of shareware ever made and still not making any money.

 DroidXplorer big in China?

According to an email DroidXplorer will be preinstalled on devices, and be featured on a set of app stores. For free.

 QuickTip: PayPal IPN - Complex Pass Through Data

Send complex data in the custom field that you use to match a payment with a customer, order or whatever you need.

 Would this interest you?

Page 1 / 11