为什么这个 PHP header() 重定向会陷入无限循环?

发布于 2024-12-03 00:58:37 字数 464 浏览 2 评论 0原文

我有这段代码,应该获取当前日期,将其映射到设定的结束日期,并在当前日期超过结束日期时重定向。每当我将 $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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

海之角 2024-12-10 00:58:37

如果针('close.php')位于大海捞针($_SERVER['PHP_SELF'])的开头,则 strpos 可以返回 0。这将被 PHP 视为“假”,因为您没有使用严格的比较运算符。

必须使用严格比较运算符来检查这种情况:

if ($promoend && (strpos(...) !== FALSE)) {
   header(...);
}

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(...);
}
离鸿 2024-12-10 00:58:37

if ($promoend && !strpos($_SERVER["PHP_SELF"],"closed.php")) {
    header("Location: ".$environment->root."/closed.php");
}

...可能应该是...


if ($promoend && strpos($_SERVER["PHP_SELF"],"closed.php")!==true) {
    header("Location: ".$environment->root."/closed.php");
}

因为 strpos() 并不总是返回布尔值,所以您必须使用 PHP 等价运算符。


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.

|煩躁 2024-12-10 00:58:37

假设您的日期计算正确,原因是 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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文