Skip to content
Advertisement

How to redirect to previous page in PHP without http_refferer

I want to redirect to the preverious page. I don’t want to use the PHP $_SERVER[‘http_reffer’]

I’m using PHP friendly URLs if it is important. My actual solution is:

header("Location: http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);

This doesn’t work and i get this Message in Firefox: ‘The page isn’t redirecting properly’

Is there any solution?

Advertisement

Answer

You are trying to redirect to the same location you are currently at, which intern redirects again and again. You must either use http_reffer or you need to track the previous page loaded for the user and store it somewhere like the session. You will need a default location to redirect to in either case as there is no guarantee it will be set.

    session_start();
    $_SESSION['last_location'] = "https://{$_SERVER["HTTP_HOST"]}{$_SERVER["REQUEST_URI"]}";
    session_write_close();
    session_start();
    if (isset($_SESSION["last_location"])) {
        header("Location: {$_SESSION["last_location"]}");
    } else {
        header("Location: {$_SERVER["HTTP_HOST"]}");
    }

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement