views:

39

answers:

1

Hi Folks,

I am a novice in Facebook development and PHP. I just started today and I would like to know what the following code snippet does,

<?php

define('FACEBOOK_APP_ID', '123423');  
define('FACEBOOK_SECRET', '3eesewee3e');  

function get_facebook_cookie($app_id, $application_secret) {  
  $args = array();  
  parse_str(trim($_COOKIE['fbs_' . $app_id], '\\"'), $args); //Why??  
  ksort($args);  
  $payload = '';  
  foreach ($args as $key => $value) {        
    if ($key != 'sig') {//Why checking not equals to 'sig'  
      $payload .= $key . '=' . $value;  
    }  
  }  
  if (md5($payload . $application_secret) != $args['sig']) {//why is this checking  
    return null;  
  }  
  return $args;  
}  

$cookie = get_facebook_cookie(FACEBOOK_APP_ID, FACEBOOK_SECRET);  

?>

I kind of understood the PHP functions and their usage. I would like to know why is it done this way?

I would like to know the explanations for the lines with comments //why. I am kind of not so sure whats going to and fro during this communication and why are we doing these kind of checking etc.

Thanks for your time.

Regards, Abhishek

A: 

The first queried line is filling $args with keys/values from the cookie.

The second queried line is in a loop of the keys of $args. It's ignoring 'sig' because this is a signature and is not going to be hashed.

The third queried line checks that the hash of the payload matches the signature.

Basically, what this code is doing is parsing the cookie, sorting the keys into a standard order, taking a hash of the sorted keys and comparing that hash with the signature. If the signature doesn't match the hash then the cookie has been tampered with.

The $args array needs to be sorted with a standard sorting function, because the order of the data affects the hashed value.

Skilldrick
Perfect skilldrick ! Thanks a bunch!!
Abhishek
No worries :) ...
Skilldrick