GET变量和IF语句

时间:2013-10-05 21:45:19

标签: php if-statement get

我对这个简单的if语句有疑问:

$type = $_GET['type'];
if ($type !== 1 || $type !== 2) {
    header('Location: payment.php');
    exit;
}

只允许输入 1 2 ,但......

  1. www.example / succeed.php?type = 1 - 重定向回payment.php
  2. www.example / succeed.php?type = 2 - 重定向回payment.php
  3. www.example / succeed.php?type = 3 - 重定向回payment.php
  4. 最后一个例子没问题,但我不知道为什么它在第一个和第二个例子中重定向。

3 个答案:

答案 0 :(得分:4)

!==是身份运营商;所以它也会检查类型。

但$ _GET,$ _POST,...数组中的数据是字符串。所以你还需要检查字符串:

if ($type !== "1" && $type !== "2") /* ... */

同时检查$a !== $x && $a !== $y是否始终为真(如果$x !== $y)。所以在这里使用||

答案 1 :(得分:1)

试试这个:

if (!($type == 1 || $type == 2)) {
    header('Location: payment.php');
    exit;
}

这可以用Anything other than type is 1 or 2

表示

答案 2 :(得分:0)

如果你的意思是只有值为1和2的类型应重定向你应该尝试这个代码

if ($type === 1 || $type === 2) {
    header('Location: payment.php');
    exit;
}
相关问题