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

前端 未结 5 1321
你的背包
你的背包 2020-12-17 08:35
$_SESSION[\"some_value\"] = 4;
header(\"Location: another-file.php\");
$_SESSION[\"some_value\"] = 5;

what\'s the value of $_SESSION[\"some_v

5条回答
  •  失恋的感觉
    2020-12-17 09:12

    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.

提交回复
热议问题