Finding the HTTP Referrer in CodeIgniter
I’ve noticed a lot of search engine traffic hitting my post on custom 404 error handling in CodeIgniter recently, looking for information on how to find the HTTP referrer in CI. So this is just a quick post to give those people what they’re looking for!
While you can use the native PHP
$_SERVER[‘HTTP_REFERER’] predefined variable, there is a CI version as well.
The User Agent class has a wealth of useful functions for finding information about the visitor; including their browser capabilities, operating system or even if they’re a bot. The one we’re interested in here though, is
Once you have loaded the User Agent class, all you need to do is run
$this->agent->referrer() and you will be returned a string containing the referring URL, or an empty string if there is no referrer.
If you simply want to test whether the visitor was referred from another site or not, you can use
$this->agent->is_referral(), which will return a boolean value.
While you’re poking about with the User Agent class, take 5 minutes to check out the other functions too as they are mighty handy. For instance,
$this->agent->is_mobile() could let you easily redirect mobile users to an optimized mobile site, or you could use
$this->agent->robot() to check if you’re dealing with a known “bad” robot, that may not necessarily honour robots.txt (they do exist, sadly).
Posted on Wednesday, 14th July 2010.
Sorry, feedback is now closed on this post, but please feel free to get in touch if you would like to talk about it!
Once again, Kris, you helped solve one of my problems on a website I was working on. For some reason $_SERVER[“HTTP_REFERER”] was working for me in Google Chrome, but not always with Firefox or Internet Explorer. Using the User Agent class worked for me in all three browsers.
Keep up the good work and thanks for sharing!
Happy to help as always Kent!
Very odd that you were having issues with the vanilla PHP version, never experienced that before…