120x600

Getting Started - The Model

First of all you need a website built with CodeIgniter. Chances are, you might already have one of those.

You need to register that website with Facebook so that you can get a Facebook Application Id for your site. The process does not take too long, (it took me about a minute for the site your reading right now) and you can do it at http://developers.facebook.com/setup/.

My tutorial is running on CodeIgniter version 1.7.2, on a shared hosting CPanel-type environment at site5.com webhosting. I'm sure it will work on other server configurations, and possibly even other versions of CodeIgniter.

If you want to see the tutorial actually work the way it was supposed to, you'll probably want to log in using that blue button near the top of the page.

Model vs. Library

My idea was to adapt the sample code that Facebook provided here (the code in question is the 3rd code block under the section "Single Sign-on") into the MVC pattern that CodeIgniter so brilliantly implements. Other solutions use a Facebook Connect library. I decided to use a Model, instead of a Library.

The reason I chose Model over Library is because Models are used for getting data, and I wanted to get data from Facebook. This is the first time I've ever used a Model for anything other than connecting to a mysql database on my own server, so this was a novel thought for me. I don't pretend to be a MVC or a CodeIgniter expert, so if I'm a complete idiot for using a Model instead of a Library, please let me know in the comments section below. Go ahead; I can take it.

Below is my Model I constructed. If you are following along, copy it, paste it, and save it as facebook_model.php in your application/models folder in your CodeIgniter installation. You're going to need to change the values of $app_id and $application_secret.

<?

class facebook_model extends Model{
	function facebook_model(){
		parent::Model();
	}

	function get_facebook_cookie() {
  		$app_id             = '123456789012345';
		$application_secret = '1234abcd5678efab1234cdef5678';

		if(isset($_COOKIE['fbs_' . $app_id])){
  			$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 . $application_secret) != $args['sig']) {
    				return null;
  			}
  			return $args;
  		}
  		else{
			return null;
  		}
	}

	function getUser(){
		$cookie = $this->get_facebook_cookie();
		$user = @json_decode(file_get_contents(
    				'https://graph.facebook.com/me?access_token=' .
    				$cookie['access_token']), true);
		return $user;
	}

	function getFriendIds($include_self = TRUE){
		$cookie = $this->get_facebook_cookie();
		$friends = @json_decode(file_get_contents(
    				'https://graph.facebook.com/me/friends?access_token=' .
    				$cookie['access_token']), true);
		$friend_ids = array();
		foreach($friends['data'] as $friend){
			$friend_ids[] = $friend['id'];
		}
		if($include_self == TRUE){
			$friend_ids[] = $cookie['uid'];			
		}	

		return $friend_ids;
	}

	function getFriends($include_self = TRUE){
		$cookie = $this->get_facebook_cookie();
		$friends = @json_decode(file_get_contents(
    				'https://graph.facebook.com/me/friends?access_token=' .
    				$cookie['access_token']), true);
		
		if($include_self == TRUE){
			$friends['data'][] = array(
				'name'   => 'You',
				'id' => $cookie['uid']
			);			
		}	

		return $friends['data'];
	}

	function getFriendArray($include_self = TRUE){
		$cookie = $this->get_facebook_cookie();
		$friendlist = @json_decode(file_get_contents(
    				'https://graph.facebook.com/me/friends?access_token=' .
    				$cookie['access_token']), true);
		$friends = array();
		foreach($friendlist['data'] as $friend){
			$friends[$friend['id']] = $friend['name'];
		}
		if($include_self == TRUE){
			$friends[$cookie['uid']] = 'You';			
		}	

		return $friends;
	}
}

?>

The first function, (or second, if you're counting the constructor,) get_facebook_cookie() is stolen and slightly modified from sample code provided by Facebook in their documentation. You will need to modify the values for $app_id and $application_secret to the values that you got from Facebook when you registered your site with Facebook. (You did register your site with Facebook, right?)

I will admit that I don't understand how the function works. But if you theses lines in a function in your controller


	$this->load->model('facebook_model');
	$cookie = $this->facebook_model->get_facebook_cookie();
you would have available to you the values in $cookie['uid'] (the logged in Facebook user's id) and $cookie['access_token'] (a string you need to access user information from Facebook).

Here's what the other functions do:

Mostly I just use getUser() and getFriendsArray(). The other ones are there because they were baby steps in creating the last one, but I left them in in the small chance that they might be useful to someone.

You don't necessarily need to know right now what json_decode or file_get_contents do, but if you are curious (or just want to be smarter) you can read about them at php.net.

Some people reading this may wonder what the @ sign is doing in front of the json_decode function. It suppresses errors. When a user logs in to a Facebook connected site, Facebook adds a cookie to the user's computer for that site's domain. If the user then logs out of Facebook, but not on the Facebook connected site, that cookie doesn't get erased right away. The file_get_contents function will try to get info from Facebook using info stored in the cookie, but Facebook won't let that happen since the user logged out of Facebook, and an error message occurs. The cookie gets erased in the process (well, actually, by a different process, but at about the same time) so if the user refreshed the page the error would go away. But I'd rather the error message not show up in the first place; it makes your site look broken.

Go to page 3

Comments

fajar sulaksono

8 August 2010 11:28 pm

great job kent :)

Your comment will appear once it is approved.

  • (required)
  • (required - will not be published)
  • (optional)