Header order of execution / evaluation
When you push submit it would seem like it should evaluate the header in foo() before the next 开发者_如何学JAVAone, but the next one gets executed first?
<?php
function foo(){
header("Location: http://".$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF']."?message=XYZ");
}
if($_POST['action'] == 'gogogo'){
foo();
header("Location: http://".$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF']."?message=ABC");
}
echo "<form action='".$_SERVER['SCRIPT_NAME']."' method='post'>";
echo "<input type='hidden' name='action' value='gogogo' />";
echo "<input type='submit' />";
echo "</form>";
echo "Contents of \$_GET['message']: ";
if(isset($_GET['message'])) {
echo $_GET['message'];
} else {
echo "Empty";
}
?>
It does evaluate the XYZ first, then moves on to the next line in the script which overwrites it with the ABC header.
use exit after setting the header to terminate script execution
EDIT
header() does not automatically do the redirect for you, because you may want to send several different headers. It simply queues a series of response headers, ready for when your script does output its response. Using exit will trigger the actual sending of the response headers
Your sending out the same header with 2 different values so the 2nd one overrides the first!
Either remove the foo()
call or add an exit()
statement in the function.
精彩评论