php redirect fails and does not do anything
i have just a simple php file with this line of code.
<?php header("Locati开发者_JAVA技巧on: MyBooks.php", true); exit();?>
Form 1 submits form to this simple php file and this file supposed to redirects to MyBooks.php within the same directory.
i just do not get it, why it does not redirects ?
there's no errors reported.
Seems like an issue in server you are running: http://social.msdn.microsoft.com/Forums/expression/en-US/db37d2ea-65ef-40ad-8a25-62a846a5d00d/php-headers-and-redirect
So you have to manually specify response code to 302 before sending location header:
header('HTTP/1.0 302 Found');
header('Location: http://localhost/MyBooks.php');
exit;
And remember to use absolute URL in Location
.
It's possible that you have already sent some output through your script (which could be just whitespace), in which case you cannot send headers anymore.
Test it with this code:
if (headers_sent()) {
die("Error: headers already sent!");
}
else {
header("Location: MyBooks.php", true);
exit();
}
If this prints an error, then you need to make sure that there's no output at all going out before the header
call. Check that:
- You do not
echo
anything at all (or otherwise output any HTML) before theheader
call - There is absolutely no whitespace before the
<?php
start tag or the?>
end tag (if present) in your PHP scripts
Update: How to check HTTP headers using Chrome
- Select the Network tab
- Choose Documents from the menu just above the console to narrow down the list on the right
- Choose the only resource that the filter matches from the list on the right (
http://localhost/
here) - Click the Headers tab
The only way that i could do that was :
$url = "http://www.google.com";
echo "<script>window.open('".$url."','_self');</script>";
Regards
You can also combine the two header calls into:
header('Location: http://localhost/MyBooks.php', true, 302);
exit;
So you won't need to remember the format/description of the HTTP Status code. The signature of the header function is
void header ( string $string [, bool $replace = true [, int $http_response_code ]] )
I thought no problem in this code check the execution come this line or not,
try without boolean
<?php header("Location: MyBooks.php); exit();?>
I had this problem and it was due to multiple locations being set in the header before the script ended.
<?php
// WARNING: BAD CODE
if($thisShouldBeTrue) {
header('Location: http://www.example.com');
}
if($weShouldNeverGetHere) {
header('Location: http://www.otherexample.com');
}
?>
I thought that php would redirect immediately at the first header and never get to the second if block. I was wrong. Always die() or exit after a redirect if your intent is to go there immediately.
<?php
// CORRECT
if($thisMightBeTrue) {
header('Location: http://www.example.com');
die();
}
if($orThisMightBeTrue) {
header('Location: http://www.otherexample.com');
die();
}
?>
精彩评论