简体   繁体   中英

How to get refering URL when redirected from some page to another page

I am redirecting from several pages to dev.php using php header

<?php header(Location: dev.php); ?>

I want to know from where i have been redirected here.

I have tried

<?php
print "You entered using a link on ".$_SERVER["HTTP_REFERER"];
?>

but it dosent work as $_SERVER["HTTP_REFERER"]; only works if you access dev.php using <a href="dev.php">Go to Developer Page</a>

So how can i get the referring URL?

Try something like below.

<?php header(Location: dev.php?referrer=$_SERVER[PHP_SELF]); ?>

OR

header('Referer: '.$_SERVER['PHP_SELF']);
header(Location: dev.php);

If above methods don't work, You will have to go with sessions.

You can pass the variable in GET:

<?php header('Location: dev.php?backurl='.$_SERVER[PHP_SELF]); ?>

And then take it in this way:

$backurl=$_GET['backurl'];

You need to add the referer to the header manually:

header("Referer: http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']); // current page
header("Location: dev.php");

You can also do it using CURL. Have a look at an example function for that here: PHP - Referer redirect script

$_SERVER["HTTP_REFERER"] = 'YOUR_URL';
header('Location: dev.php');
exit(0);

The referer header is rather unreliable, there are antivirus software and firewalls out there that filter it completely. The only thing you can pretty safely rely on are cookies and with them, sessions.

Cookies are stored on the client side, in the browser, therefore can be manipulated, but if you are storing non-critical information, they can be enough.

Sessions nowadays rely on cookies as a means of starting them. A randomly generated hash is stored in a cookie, the corresponding data is stored on the server linked to this hash. When the client requests the next page, this data is retrieved. For more information about sessions read the corresponding section of the PHP manual .

As I wrote, sessions rely on cookies nowadays and you shouldn't do that unless you are aware of the security implications. You can however use URL parameters to pass the session ID along.

On a side note: in order to use cookies (and with them sessions) both the setting and the final URL must be on the same domain. If this isn't the case, you can use request parameters to pass the information along.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM