Why does this PHP header() redirect get stuck in an infinite loop?
I have this piece of code that is supposed to get the current date, comapre it to a set end date, and redirect if the current date is past the end date. Whenever I set the $promoend to a past date, I get stuck in a redirect loop.
The if() block should only redirect if the promotion has ended and I am not on the closed.php page already.
$currentdate = new DateTime("now");
$promoend = new DateTime("11/01/2010 00:00:00");
$promoend = $currentdate->diff($promoend)->invert;
if ($promoend && !strpos($_SERVER["PHP_SELF"],"closed.php")) {
header("Location: ".$environment->root."/closed.php");
开发者_开发知识库}
Any idea why this is caught in a loop?
strpos can return 0 if the needle ('closed.php') is at the start of the haystack ($_SERVER['PHP_SELF']). This will get treated as 'false' by PHP, as you're not using a strict comparison operator.
You MUST use the strict comparison operator to check for this case:
if ($promoend && (strpos(...) !== FALSE)) {
header(...);
}
if ($promoend && !strpos($_SERVER["PHP_SELF"],"closed.php")) {
header("Location: ".$environment->root."/closed.php");
}
...should probably be...
if ($promoend && strpos($_SERVER["PHP_SELF"],"closed.php")!==true) {
header("Location: ".$environment->root."/closed.php");
}
Because strpos() does not always return a boolean so you have to use the PHP equivalence operator.
Assuming your date calculations are correct the reason is, is that strpos is returning 0 because the string you are looking for in PHP_SELF is at the 0 position.
You have to use !== "" instead of just !val because 0 is the same as "" is the same as NULL
精彩评论