PHP - header("Location:") inside a function redirects without calling function

23,735

Solution 1

That should not happen. Either you are calling the function somewhere, or another part of the code is writing out the header. Can you add some debug to that function to check?

Solution 2

In addition to the feedback already given. It is a good idea to exit after you redirect.

function headerLocation($location,$message)
{
    $_SESSION['output'] = $message;
    header("Location: ". $location);
    exit;
}

Solution 3

The redirect happens too fast for the $_Session to be written properly. Use

session_write_close();

before the header call.

Edit: Removed the ridiculous $ in front of the function call.

Solution 4

Just a guess, perhaps you should buffer your output ( ob_start() ) This will cause headers to be sent only when the output is flushed, allowing the rest of your code to execute.

Solution 5

It makes no sense for the header() function to redirect without calling headerLocation() first.

My guess is that you're not seeing $_SESSION['output'] hold $message, and that makes you think the function is not being executed. Try writing to a new file instead, does that work? I bet it will.

The reason $_SESSION might not be holding your values is probably because of P3P and your browser and / or PHP configuration.

Also, are you sure you don't wanna call die() / exit() after the header() redirect?

Share:
23,735
Gal
Author by

Gal

Updated on July 09, 2022

Comments

  • Gal
    Gal almost 2 years

    I'm using a function called headerLocation() in order to redirect properly. This is the pertinent part of the function, I'm using it to redirect and then display an appropriate message (personal preference).

    function headerLocation($location,$message)
    {
        $_SESSION['output'] = $message;
        header("Location: ". $location);
    }
    

    The problem is, when I run the script, the header("Location: ". $location); part is activated without even calling the function (when I initially require it for php parsing). This renders the function useless.

    Is there any way around this?