Facebook Development and $_SERVER[‘HTTP_REFERER’]

F

If you are new to creating Facebook applications or even if you’re not.  When you go to use $_SERVER[‘HTTP_REFERER’] you might be in for a surprise when this _SERVER variable does not exist!

Just recently I encountered this problem, when I thought about it for a few seconds it made sense why the variable wasn’t there.  Your server cannot properly track the history because every page request in your Facebook application occurs through a request from a Facebook server, not the user them self.

The solution to this problem is relatively simple, assuming your web site has at least ONE file that you include on every single page of the site.  Either a header.php, a config.php, etc…  If you don’t have this, you might be required to copy and paste the code into each page of your web site.

if (array_key_exists(‘current_url’, $_SESSION))
     $_SESSION[‘HTTP_REFERER’] = $_SESSION[‘current_url’];

$_SESSION[‘current_url’] = $_SERVER[‘REQUEST_URI’];

By adding the following code to a global template, $_SESSION[‘HTTP_REFERER’] now contains what the previous page the user was one.

Please note, this might not work right out of the box for you.  A couple of problems can occur.  My applications are built with a framework and $_SERVER[‘REQUEST_URI’] is built perfectly for me because it doesn’t use query string variables.

So, if your application requires the query string as well.  Simply update the code and append the following (this should go after setting the current_url):

if (!empty($_SERVER[‘QUERY_STRING’]))
     $_SESSION[‘current_url’] .= “?” . $_SERVER[‘QUERY_STRING’];

Hopefully this comes in handy during your next Facebook application.

About the author

By Jamie

My Books