The only thing we need to make this work is a unique identifier sent to us on each server call from the client. Something that is not obvious and cannot easily be guessed; since there is no true security in this process. The easiest thing to use is the session id that is created by the server on the first visit. No matter the server-side language, if it supports session it will provide you with a unique session id. Below is some example PHP code to get our session id:
<?php
$sessionId = session_id();
?>
We will want to retrieve this id on the first page load (usually when we load the Flash application). The process would be something like this:
<?php
session_start();
if (array_key_exists('sessionId', $_REQUEST)) {
$sessionId = $_REQUEST['sessionId'];
session_id($sessionId);
} else {
$sessionId = session_id();
}
?>
On each page request this will look for the session id in the URL or it will generate a new one. After this process we would pass the $sessionId to Flash so they can send it back each time allowing us to maitain our session in a session-less environment.
You may have noticed that this is an incomplete example because we haven't stored anything in our session to maintain. To make this example complete, we will want to retrieve the "current user" from our database. In the else statement above, we would need to perform a query to retrieve the user. Once retrieved, we can store the user in the session and use it on each subsequent call when our session is already set.
Have I confused you even more? Below is a stripped down example of doing this with an iframed Facebook application:
<?php
session_start();
if (array_key_exists('sessionId', $_REQUEST)) {
$sessionId = $_REQUEST['sessionId'];
session_id($sessionId);
if (array_key_exists('user', $_SESSION)) {
$user = $_SESSION['user'];
} else {
echo '<script>window.top.location="http://apps.facebook.com/<myapphere>";</script>';
exit;
}
} else {
$sessionId = session_id();
$userId = validateFacebook();
$user = fakeFunctionToGetOurUser($userId);
$_SESSION['user'] = $user;
}
function validateFacebook() {
if (array_key_exists('fb_sig', $_REQUEST)) {
return $_REQUEST['fb_sig_user'];
} else {
echo '<script>window.top.location="http://apps.facebook.com/<myapphere>";</script>';
exit;
}
}
I hope that helps clear things up. For those of you out there who are looking for a more completed Facebook iframed example, I hope to have that soon. Enjoy!
Published on Jan 17, 2011
Tags: Facebook
| session
| PHP