代码之家  ›  专栏  ›  技术社区  ›  ilhan

是不是\u int()无法在PHP中检查$\u GET?

  •  7
  • ilhan  · 技术社区  · 14 年前

    <?php
    $id = $_GET["id"];
    
    if (is_int($id) === FALSE)  {
        header('HTTP/1.1 404 Not Found');
        exit('404, page not found');
        }
    ?>
    

    它总是进入if内部。

    7 回复  |  直到 14 年前
        1
  •  33
  •   Matthew    11 年前

    is_int 数据类型 是整数,但是 $_GET 将是一个 字符串。 因此,它总是会回来的 false .

    $id = isset($_GET['id']) ? (int) $_GET['id'] : null;
    
    if (!$id) { // === 0 || === null
      header('HTTP/1.1 404 Not Found');
      exit('404, page not found');
    }
    

    但是一个更健壮的解决方案将涉及某种类型的输入字符串验证/过滤,比如PHP的内置 filter_input_array() .

    (这篇文章于10月13日编辑,因为它仍在接受投票,措辞有些混乱。)

        2
  •  5
  •   salathe    14 年前

    is_int 检查 类型 (即。 string )值,而不是它是否包含类似整数的值。为了验证输入是否是整数字符串,我建议 ctype_digit 或整数 filter ( FILTER_VALIDATE_INT 这样做的好处是将值实际更改为整型(integer)。当然你也可以用 (int) .

        3
  •  3
  •   Powerlord    14 年前

    注:测试变量是否为 数字或数字字符串(例如 表单输入,始终是字符串), is_numeric() .

        4
  •  1
  •   Keith Palmer Jr.    14 年前

    任何用户输入都是以字符串的形式出现的,因为PHP无法告诉您期望的数据类型。

    <?php
    $id = $_GET["id"];
    
    if ((int) $id == 0)  {
        header('HTTP/1.1 404 Not Found');
        exit('404, page not found');
        }
    ?>
    
        5
  •  1
  •   Jason    14 年前

    尝试使用 is_numeric is_int 是数字吗 检查是否给定了可以是数字的东西( $_GET 是\u int int

        6
  •  0
  •   user3109929    10 年前
        7
  •  0
  •   chafreaky    9 年前

    if(preg_match('/^\d+$/',$_GET['id'])) {
      // is an integer
    }