Quick start on new Facebook PHP SDK (IFrame based)

This post is more than couple year old. It solved the issues when the SDK was first released and facebook had lack of documentation. However, now facebook has very rich set of documnetation and you should follow that instead!

The new Facebook API has already spread over the application developers and if you’re like me, you’ve already got your hands dirty to see how this new thing works. If you have tried to follow the documentation to authorize/get session in your canvas application, it is likely you have already hit roadblocks. Well, I am no savior but I have glued together a few clues and got it working for myself.

I am assuming that you have already created your application by following the Getting Started section from the official documentation. Also, this is for IFrame based applications only.

Enough talking, let’s get some code.

Step 1: Get the new SDK

Download the new SDK from github. We will only need the facebook.php file from the src folder. In our project directory, let’s create a folder called “lib” and put the file there.

Step 2: A configuration file

Let’s now create a configuration file to store our facebook configuration. Let’s name it config.php. Here goes the source:

1<?php
2
3define("FACEBOOK_APP_ID", '113795715321151');
4define("FACEBOOK_API_KEY", '064baf5fb98de050cd7b9a001ca1988b');
5define("FACEBOOK_SECRET_KEY", '430f43c01f6dfe02c284b4545976f9ce');
6define("FACEBOOK_CANVAS_URL", 'http://apps.facebook.com/emran-test-app/');

Step 3: Application Main Page

This file will be the main entry point to our facebook application. It just instantiates the facebook object, sets the configuration and checks for a valid session. If it does not find a valid session, it redirects to the login page. For first time visitors, it will be the authorization page. On later requests, the operation will occur in the background – without any user interaction.

1<?php
2
3include_once 'lib/facebook.php';
4include_once 'config.php';
5
6$facebook = new Facebook(array(
7 'appId' => FACEBOOK_APP_ID,
8 'secret' => FACEBOOK_SECRET_KEY,
9 'cookie' => true,
10 'domain' => 'phpfour.com'
11));
12
13$session = $facebook->getSession();
14
15if (!$session) {
16
17 $url = $facebook->getLoginUrl(array(
18 'canvas' => 1,
19 'fbconnect' => 0
20 ));
21
22 echo "<script" . " type='text/javascript'" . ">top.location.href = '$url';</script>";
23
24} else {
25
26 try {
27
28 $uid = $facebook->getUser();
29 $me = $facebook->api('/me');
30
31 $updated = date("l, F j, Y", strtotime($me['updated_time']));
32
33 echo "Hello " . $me['name'] . "<br />";
34 echo "You last updated your profile on " . $updated;
35
36 } catch (FacebookApiException $e) {
37
38 echo "Error:" . print_r($e, true);
39
40 }
41}

You might be wondering – it’s pretty straight-forward, so what’s the catch ? Well, to be honest, the documentation does not have the “canvas” parameter mentioned anywhere which does the primary magic here. Also, if you do not use the javascript trick, then you end up with an authorization dialog with full facebook UI within the iframe itself (see below).

CodeIgniter Version

Here is the CodeIgniter version of the above example. The significance is that CodeIgniter removes the values from the $_GET super global – which is required for the library to work. We thus re-populate it on the constructor ourselves and start a session to share data among subsequent page visits.

1<?php
2
3include_once APPPATH . 'libraries/facebook-php-sdk/facebook.php';
4
5class Test extends Controller
6{
7 private $facebook;
8
9 public function __construct()
10 {
11 parent::__construct();
12 parse_str($_SERVER['QUERY_STRING'], $_GET);
13 session_start();
14 }
15
16 public function index()
17 {
18 $this->facebook = new Facebook(array(
19 'appId' => $this->config->item('facebook_app_id'),
20 'secret' => $this->config->item('facebook_secret_key'),
21 'cookie' => true,
22 'domain' => 'phpfour.com'
23 ));
24
25 $session = $this->facebook->getSession();
26
27 if (!$session) {
28
29 $url = $this->facebook->getLoginUrl(array('canvas' => 1, 'fbconnect' => 0));
30 echo "<script" . " type='text/javascript'" . ">top.location.href = '$url';</script>";
31
32 } else {
33
34 try {
35
36 $uid = $this->facebook->getUser();
37 $me = $this->facebook->api('/me');
38
39 $updated = date("l, F j, Y", strtotime($me['updated_time']));
40
41 echo "Hello " . $me['name'] . "<br />";
42 echo "You last updated your profile on " . $updated;
43
44 } catch (FacebookApiException $e) {
45
46 echo "Error:" . print_r($e, true);
47
48 }
49 }
50 }
51}

Hope I am able to help a few people.

Cheers!

Enterprise PHP

I presented this talk on the Soft Expo 2010 – the largest software fair in Bangladesh. The intention was to clear some of the misconception about PHP, the growth of PHP, how it can fit in the enterprise now, etc.

After these, I shed light on some topics that a company/developer should keep in mind in order to write good software in PHP. This was followed by live session on caching, mysql query optimization, use of Xdebug, etc.

So here goes the presentation:

And a big thanks to Ivo Jansch’s “PHP in the real wolrd” presentation, from where I took inspiration.

Cheers!

Changing the default controller naming convention in CodeIgniter

CodeIgniter is one of my favorite framework and I often use it for developing application quickly. Although it is very flexible in most cases, I find its naming convention to be strict. Many times I have faced this problem when my controller’s class name and a model/library’s class names are the same – a Fatal error is inevitable and I have to forcefully change the name of the conflicting class to something less desirable (say from Users to UsersModel). Today I wanted to end this problem.

So I extended the CI_Router core class and made change to the _validate_request method. Now I can name my controller classes in this fashion: UsersController and it resides on the file system as controllers/UsersController.php. If you’ve tried other established frameworks, you should notice that this naming convention is widely used. So, if you have the same need, then just download the MY_Router.php file and put it on your application/libraries folder. That’s it.

Here is how your controller would start:

[cc lang=’php’]
(more…)