views:

893

answers:

6

Hi

I am creating a website and on one particular page, am wanting to send the user back to the previous page. I am fairly new to PHP/HTML and have been using some existing code for ideas and help.

The existing code uses the following method:

if (! empty($HTTP_REFERER)) 
{
    header("Location: $HTTP_REFERER");
} else 
{
    header("Location: $CFG->wwwroot");
}

However, when I use this code the HTTP_referer is always treated as empty and the user redirected to the root page. Any obvious flaws in this code?

+8  A: 

You need to use:

$_SERVER['HTTP_REFERER']
jonstjohn
A: 

Also note that the referer header might be empty or missing anyway, so you shouldn't rely on it at all..

kkyy
+7  A: 

Don't rely on the HTTP Referrer being a valid or even non-empty field. People can choose to not have this set leaving any checks for that variable going to the empty side of the IF-ELSE clause.

You can guard against this by sending along a parameter in either the URL or POST parameters that would hold a value that you can use to redirect the user back to.

random
+1. Referrers are inherently unreliable. Use a parameter to direct the user where you want them to go after the form.
bobince
A: 

You should use

$_SERVER['HTTP_REFERER']

However look at the register_globals configuration in php.ini, it should be turned off due to security reasons. You can read more on PHP Manual site.

michal kralik
A: 

If you wanted to send the person back to the previous page and have it work regardless of the referrer being set correctly, you can append a GET parameter to the URL (or POST).. you will need to encode the URL.. Something like

http://www.domain.com.au/script.php?return=http%3a%2f%2fwww.domain.com.au%2fthis-is-where-i-was%2f

You can use PHP's urlencode() function. Also use strip_tags() to for security if you're going to echo it elsewhere to the page.

alex
+1  A: 

isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';