Hi! I'm currently reworking my site, so although this content is still online things may change or look odd. Please get in touch to find out how I can help you!

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 referrer().

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).

Tags: CodeIgniter PHP

Feedback

Sorry, feedback is now closed on this post, but please feel free to get in touch if you would like to talk about it!

  1. Kent on

    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!

  2. Kris on

    Happy to help as always Kent!

    Very odd that you were having issues with the vanilla PHP version, never experienced that before…

Or find posts by tag →

Friends & Influences

  1. Aching Brain
  2. Andy Budd
  3. Anthony Killeen
  4. Ben Everard
  5. Cameron Moll
  6. Dan Cederholm
  7. Dan Mall
  8. Dave Shea
  9. Elliot Jay Stocks
  10. Jamie Knight
  11. Jamie Rumbelow
  12. Jason Santa Maria
  13. Jeff Croft
  14. Jeffrey Zeldman
  15. Jeremy Keith
  16. Jon Hicks
  17. Khoi Vinh
  18. Mark Boulton
  19. Matt Croucher
  20. Nocturnal Monkey
  21. Sarah Parmenter
  22. Shaun Inman
  23. Simon Collison
  24. Tim Van Damme
  25. Toby Howarth