why is my header("Location: $_SERVER['HTTP_REFERER']"); PHP function not working?

Simon Suh picture Simon Suh · Nov 3, 2011 · Viewed 39.7k times · Source

It works when I input

header("Location: http://www.google.com");

but it doesn't work when I have

header("Location: $_SERVER['HTTP_REFERER']");

I want to redirect the page to whatever page it came from.

Answer

Rok Kralj picture Rok Kralj · Nov 3, 2011

Try it: :)

if (!empty($_SERVER['HTTP_REFERER']))
    header("Location: ".$_SERVER['HTTP_REFERER']);
else
   echo "No referrer.";

However, for determining which page user came from, I'd rather use session variable, which gets reset at every page:

session_start();
echo "Previous page:", $_SESSION['loc'];
$_SESSION['loc']=$_SERVER['PHP_SELF'];

ps: This only works for local pages, you cannot track other websites.