Adding Facebook Connect functionality to your application

PHP, Tutorials

In this tutorial we are going to use Facebook Javascript SDK.

Here is how you can add Facebook Connect functionality to your PHPRunner application.

1. Register your website to get an app id.

http://developers.facebook.com/setup/

Later you can see your application settings at http://www.facebook.com/developers/apps.php

2. Add ‘Login with Facebook’ button to your application

The natural place to add this button is a login page.

Open login page in Visual Editor. Make sure ‘Show borders’ option is turned on. Insert a new table row below ‘Remember password’. Merge two table cells that belong to this row. Make this cell centered.

Put cursor into this table cell and switch to HTML mode. Paste the following code there:

Login with
 Facebook

3. Add code to AfterAppInit event

Now its time to add server-side code that logs you in and out.

define('FACEBOOK_APP_ID', 'YOUR_APP_ID_HERE');
define('FACEBOOK_SECRET', 'YOUR_SECRET_HERE');

function get_facebook_cookie($app_id, $app_secret) {
 $args = array();
 parse_str(trim($_COOKIE['fbs_' . $app_id], '\\"'), $args);
 ksort($args);
 $payload = '';
 foreach ($args as $key => $value) {
 if ($key != 'sig') {
 $payload .= $key . '=' . $value;
 }
 }
 if (md5($payload . $app_secret) != $args['sig']) {
 return null;
 }
 return $args;
}

$cookie = get_facebook_cookie(FACEBOOK_APP_ID, FACEBOOK_SECRET);

if ($cookie && getFileNameFromURL()=="login.php")
{

 // save access token in session
 $_SESSION["facebook_access_token"]=$cookie['access_token'];

 if($_GET["a"]=="logout")
 {
 setcookie('fbs_'.FACEBOOK_APP_ID, '', time()-100, '/', '');
 }
 else
 {
 $user = json_decode(file_get_contents(
 'https://graph.facebook.com/me?access_token=' .
 $cookie['access_token']));

 if ($user)
 {
 $_SESSION["UserID"]=$user->name;
 $_SESSION["AccessLevel"] = ACCESS_LEVEL_USER;
 $_SESSION["GroupID"] = "";

 header("Location: menu.php");
 exit();
 }
 }
}

This code checks if Facebook cookie exists. If cookie is found we extract Facebook access token from the cookie and query Facebook server for user settings like name. If we got to this point successfully we populate PHPRunner session variables to enable access to PHPRunner application and redirect user to the menu page. We also save Facebook access token in session variable for future use.

In case of log out we reset Facebook cookie marking it as expired.

If you have a Facebook account you can see how Facebook Connect works in sample PHPRunner application.

4. Further enhancements

We have add a possibility for our users to connect using Facebook account. Now it’s time to do something fancy.

Lets see how we can pull some additional info about current user from Facebook.

The following code snippet connects to Facebook and retrieves all available user properties.

$user = json_decode(file_get_contents(
			'https://graph.facebook.com/me?access_token=' .
			$cookie['access_token']));

More info about Facebook user object.

As an optional part you can explore user object properties right in the browser. If you want you can skip this part and jump directly to Display Facebook profile picture section.

Glad you are game to learn a bit more about Facebook API. The good thing is that you can open https://graph.facebook.com/me?access_token=YOUR_ACCESS_TOKEN URL in browser and see all available user properties there. You will need to find your access token in order to do that.

If you already implemented Facebook connect in your application and were able to connect successfully access token is stored in the cookie fbs_YOUR_APP_ID. If you have Firefox with Firebug and Firecookie extensions installed you can quickly find what’s your access token is.

Another method of finding access tokens described in this article.

Display Facebook profile picture

As manual suggests, to display profile picture you can use the following URL:

We proceed to the menu page in Visual Editor and insert PHP code snippet next to the yellow ‘username’ box. In this snippet we are going to use Facebook access token we have saved in session variable.

if ($_SESSION["facebook_access_token"])
echo '';

If everything is implemented properly you going to see your profile picture next to your name.

Yes, I’m one of those Facebook users who don’t have a profile picture. If you do, you going to see it, I promise.

Getting user email address

Getting access to additional properties requires explicit user permissions. Lets say we want to find what user email address is.

Step 1

Modify Login with Facebook button code:

Login with Facebook

perms=”email” tells Facebook our application needs access to use email address. In this case user will be presented with the following popup window:

Step 2

If permission granted you can access user email as $user->email (AfterAppInit code). For example you can display email address as a logged user name:

$_SESSION["UserID"]=$user->email;

More info about Facebook permissions.

This is it.
———————-

Make sure you join PHPRunner Facebook page.

More info on Facebook authentication.

11 thoughts on “Adding Facebook Connect functionality to your application

  1. Hey Admins,

    This is very nice. On similar lines is “Login with Google” possible?

    Could you please provide a Tutorial for that too.

    Regards

  2. Sorry I am new to phprunner and php. I go to the AfterAppInit event and add the function get_facebook_cookie($app_id, $app_secret) et… to this event but I get errors when publishing. The first part works if I remove the second part that is it shows the login to facebook button. Am I suppose to add this to the event or create a new event sorry been trying to get this to work. Thank You Steve.

  3. Nitin,

    thank you, its a reasonable suggestion and we’ll take a look into that shortly. We plan to add Twitter support as well.

  4. Steven,

    hard to tell what exactly might be wrong as this code was pulled from a working project (see link at the end of the post).

    You may want to upload your project to Demo Account and contact support to get help with this.

  5. Hope you do not mind me posting this update out here but I found what was wrong. I copy and pasted the above code into phprunner and if you at the code above all the > needs to change to > and all the & needs to change to &&. Love this post as I was looking to integrate the facebook login. Thank You for posting this code.

  6. Sergey,

    Keep up the good work with the blog… this is a very welcome addition to help support users and give us ideas on how to implement new functionality in our own apps. I also would love a tutorial on OpenID or OAuth as well…I’ll soon be implementing something like this in a project I will be working on. If I get around to it before you I’ll share my findings in the user forums under tups & tricks (PHP Runner).

    Thanks and keep up the great work!

  7. David,

    Google Maps are part of the built-in functionality. Simply set ‘View as’ type of the field that stores address to ‘Map’.

  8. Thanks For This Article. Ive Had Some Minor Issues With The HTML On This Page Converting Your Code To Its Entity Code However All Is Well Now Works Great. Thanks Again.

    Please Help With The Advanced Security Feature I Have Tried Populating
    $_SESSION[“OwnerID”] = $user->id;

  9. Hi, I have problem about logout.
    I call setcookie(‘fbs_’.FACEBOOK_APP_ID, ”, time()-100, ‘/’, ”); passing my facebook api id, but if I click in facebook login button nothing happen and I receive
    FB.login() called when user is already connected.

    You can talk about?

Leave a Reply

Your email address will not be published. Required fields are marked *