简体   繁体   中英

PHP get previous page url after redirect

I want to have a navigation bar that tells the user where they just came from. Example: Homepage -> Post

But if they are in their posts manager and click on a post, I want it to say Posts manager -> Post

I read that $_SERVER['HTTP_REFERER'] is not good enough to get the full url so that's not useful as I want the navigation bar all clickable

Any help is much appreciated!

I believe what you want is called breadcrumbs .

What to use for navigation chain storage is actually up to you. You might use even $_SERVER['HTTP_REFERER'] if you want, but that'd be unreliable as it's client-side. Usual way to store such chain is actual URI or session.

For example, you have such URI: http://www.example.com/post_manager/post

Then you can iterate through explode("/", $_SERVER["REQUEST_URI"]) to get each step.

That's basic explanation to guide you to a right direction. You can google alot of samples and snippets using keyword breadcrumbs .

On the topic of saving last visited location (the way to determine wether abonent came from manager or homepage): you can use session's variables to do that. Here's an example:

This way you can set a variable on your homepage:

<?php
    session_start(); 
    $_SESSION['previous_location'] = 'homepage';
?>

And then you just access it from another page:

<?php
    $previous_location = $_SESSION['previous_location'];
?>

It's important to set session.save_path in your PHP configuration file or your sessions might get lost.

You could do it on the client side if you use the Javascript document.referrer property. However, a better solution may be to use the global session array.

if (!isset($_SESSION['referrer'])) {
    $_SESSION['referrer'] = $current_uri;
} else {
    $previous_uri = $_SESSION['referrer'];
    $_SESSION['referrer'] = $current_uri;
}

The best solution IMO is to save the location into session, every time the user goes to a 'meaningful' page (that you want to be able to navigate back to via this feature), then simply use this array of, say, last 2 visited pages to pull up all the information. Simple and effective.

<?php
    session_start(); 
    $_SESSION['user_interactions'][] = $_SERVER['HTTP_REFERER'];

    // get previous
    $previous_page = end($_SESSION['user_interactions']);

    // list all user interactions
    foreach($_SESSION['user_interactions'] as $key => $value){
        echo $value;
        if(count($_SESSION['user_interactions'])-1 != $key) echo ">";

    }
?>

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