Is code after header(\"Location: …) executed?

2020-02-05 12:22发布

问题:

$_SESSION["some_value"] = 4;
header("Location: another-file.php");
$_SESSION["some_value"] = 5;

what's the value of $_SESSION["some_value"] ?

回答1:

The value is 5.

You can output a lot more headers than just Location headers with header, most of which you don't want to stop your code execution. If you want to stop code execution, you need to call exit explicitly.



回答2:

You should always die() or exit() after the redirect (or as pointed out by Mark B, use ignore_user_abort() ) because you can't otherwise know for certain what will happen.

Though some code will get executed after a header location redirect, it's important to note that not all code after it will necessarily get executed.

As per your example, yes, some_value will equal 5. But at some point the script will get prematurely terminated.

Take the following example:

session_start();
$_SESSION["some_value"] = 'original value';
header("Location: /index.php/test2");

$start_time = microtime(true);

for($i = 0; $i <= 100000; $i ++)
{
    password_hash($i);  // slow it down
    $_SESSION["some_value"] = $i;   
    $_SESSION['time'] = microtime(true) - $start_time;
}

$_SESSION['some_value'] = 'finished!';

If all the other answers were correct, you'd assume $_SESSION['some_value'] would equal 'finished!' -- but I ran the code and this is not the case.

Here are my results:

some_value: 174
time: 0.0026998519897461

Trial two:

some_value: 218
time: 0.0033109188079834

Trial three:

some_value: 218
time: 0.0035371780395508

Trial four:

some_value: 174
time: 0.0026431083679199

Trial five:

some_value: 174
time: 0.0027921199798584

If I implement ignore_user_abort(TRUE); in the above script then some_value does equal "finished!" so keep that in mind if you intend to do something critical like logging or database queries or sending emails after the redirect.



回答3:

Once you issue the header, you've started a race between your code and the webserver/browser. Generally, as soon as the browser receives the redirect, it'll close the connection that ran the script and start connecting to the new redirect URL. When the connection's closed, the web server will generally try to kill the script.

You might get lucky and be able to finish off anything else you wanted to do, or your might be unlucky and the script won't even be able to reach the next line after the header() call.

There is the ignore_user_abort() function, which should let your script continue regardless of the connection's status, though.



回答4:

The header command doesn't interrupt the flow of your code. Even if that is encountered, your page is still downloaded by the browser, even if it isn't show. Consider 404 pages, which (despite being errors) are still processed by the browser (though they are rendered while redirects are not).



回答5:

of course 5. You have to add exit() after such a header.