Facebook Development and $_SERVER['HTTP_REFERER'] Facebook Development and $_SERVER['HTTP_REFERER']

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.

Published on Feb 15, 2009

Tags: Facebook | php | PHP

Related Posts

Did you enjoy this article? If you did here are some more articles that I thought you will enjoy as they are very similar to the article that you just finished reading.

Tutorials

Learn how to code in HTML, CSS, JavaScript, Python, Ruby, PHP, Java, C#, SQL, and more.

No matter the programming language you're looking to learn, I've hopefully compiled an incredible set of tutorials for you to learn; whether you are beginner or an expert, there is something for everyone to learn. Each topic I go in-depth and provide many examples throughout. I can't wait for you to dig in and improve your skillset with any of the tutorials below.