为什么这个 PHP header() 重定向会陷入无限循环?
我有这段代码,应该获取当前日期,将其映射到设定的结束日期,并在当前日期超过结束日期时重定向。每当我将 $promoend 设置为过去的日期时,我就会陷入重定向循环。
if() 块仅应在促销已结束且我尚未位于 Closed.php 页面上时重定向。
$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");
}
知道为什么这会陷入循环吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果针('close.php')位于大海捞针($_SERVER['PHP_SELF'])的开头,则 strpos 可以返回 0。这将被 PHP 视为“假”,因为您没有使用严格的比较运算符。
您必须使用严格比较运算符来检查这种情况:
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:
...可能应该是...
因为 strpos() 并不总是返回布尔值,所以您必须使用 PHP 等价运算符。
...should probably be...
Because strpos() does not always return a boolean so you have to use the PHP equivalence operator.
假设您的日期计算正确,原因是 strpos 返回 0,因为您在 PHP_SELF 中查找的字符串位于 0 位置。
您必须使用 !== "" 而不仅仅是 !val 因为 0 与 "" 相同,与 NULL 相同
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