简体   繁体   中英

PHP URL from the page I was redirected

I was wondering if this is possible: I have a button on "page #1" and when clicking on it, it redirects me to /test.php file.

I would like to echo the full url of the website I was redirected from ("Page #1") to /test.php file.

I have tried $_SERVER['HTTP_REFERER'] and some other ways to that I have found from Google, but still no luck. Which raises the question, whether this is possible or not, since PHP is server-sided?

Thanks in advance

I have an idea:

In your config.php or some file, that executes on every page that a user visits, you could add a session variable:

$_SESSION['LAST_PAGE'] = $_SERVER['REQUEST_URI']

then access it when you need it. Or even use it as a 'history' of pages:

array_push($_SESSION['LAST_PAGE'], $_SERVER['REQUEST_URI'])

You can use cookies to do this. For example in Page#1.php you can set this:

<?php
$cookie_name = "url";
$cookie_value = "http://your.link.com/page#1.php";
setcookie($cookie_name, $cookie_value, time() + (3600 * 1), "/"); // Expires in 1 hour
?>

Then on your Test page (test.php) you can echo or console.log() this cookie like this:

  <?php
    if(!isset($_COOKIE[$cookie_name])) {
        echo "Cookie name '" . $cookie_name . "' is not set!";//You check if the cookie is saved
    } 
    else {
        echo "You redirected from '" . $cookie_name . "' : " . $_COOKIE[$cookie_name];
    }
    ?>

And of course you can console it like this:

<?php
  console.log($_COOKIE[$cookie_name]);
?>

Finally, there is an other way that it has to deal with JS and window.location.href or document.URL commands. You can check this answer about it.

Hope this helps, although there might be better solutions about it!

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