php validate integer

前端 未结 7 1301
南旧
南旧 2020-11-28 10:43

I`m wonder why this not working

    echo gettype($_GET[\'id\']); //returns string
  if(is_int($_GET[\'id\']))
  {
   echo \'Integer\';
  }

相关标签:
7条回答
  • 2020-11-28 11:06

    To validate form data (string) as an integer, you should use ctype_digit() It returns TRUE if every character in the string text is a decimal digit, FALSE otherwise. (PHP 4 >= 4.0.4, PHP 5)

    Reference: http://php.net/manual/en/function.ctype-digit.php

    0 讨论(0)
  • 2020-11-28 11:13

    The manual says:

    To test if a variable is a number or a numeric string (such as form input, which is always a string), you must use is_numeric().

    Alternative you can use the regex based test as:

    if(preg_match('/^\d+$/',$_GET['id'])) {
      // valid input.
    } else {
      // invalid input.
    }
    
    0 讨论(0)
  • 2020-11-28 11:15

    Can use

    $validatedValue = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);
    

    See http://php.net/filter_input and related functions.

    0 讨论(0)
  • 2020-11-28 11:19

    I take a slightly more paranoid approach to sanitizing GET input

    function sanitize_int($integer, $min='', $max='')
    {
      $int = intval($integer);
      if((($min != '') && ($int < $min)) || (($max != '') && ($int > $max)))
        return FALSE;
      return $int;
    }
    

    To be even safer, you can extract only numbers first and then run the function above

    function sanitize_paranoid_string($string, $min='', $max='')
    {
      $string = preg_replace("/[^a-zA-Z0-9]/", "", $string);
      $len = strlen($string);
      if((($min != '') && ($len < $min)) || (($max != '') && ($len > $max)))
        return FALSE;
      return $string;
    }
    

    Code from: http://libox.net

    0 讨论(0)
  • 2020-11-28 11:25

    What about intval?

    $int = intval($_GET['id']);
    
    0 讨论(0)
  • 2020-11-28 11:28

    Try:

    if(isNumeric($_GET['id'])) {
        $cast_int = (int)$_GET['id'];
    }
    
    if(isset($cast_int)) {
        echo gettype($cast_int)."<br />\n";
        if(is_int($cast_int))
        {
            echo 'Integer'."<br />\n";
        }
    } else {
        echo gettype($_GET['id'])." was passed<br />\n";
    }
    
    function isNumeric($numeric) {
        return preg_match("/^[0-9]+$/", $numeric);
    }
    
    0 讨论(0)
提交回复
热议问题