php validate integer

匿名 (未验证) 提交于 2019-12-03 08:28:06

问题:

I`m wonder why this not working

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

How to validate data passing from GET/POST if it is integer ?

回答1:

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. } 


回答2:

Can use

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

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



回答3:

What about intval?

$int = intval($_GET['id']); 


回答4:

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



回答5:

It sounds like you are checking if a string contains an integer, rather than if that variable is an integer. If so, you should check out php's regex (regular expression) functionality. It allows you to check for very specific patterns in a string to validate it for whatever criteria. (such as if it contains only number characters)

Here's the php page http://php.net/manual/en/function.preg-match.php

and here's a cheat sheet on regular expressions (to make the $pattern string) http://regexpr.com/cheatsheet/



回答6:

Try:

if(isNumeric($_GET['id'])) {     $cast_int = (int)$_GET['id']; }  if(isset($cast_int)) {     echo gettype($cast_int)."
\n"; if(is_int($cast_int)) { echo 'Integer'."
\n"; } } else { echo gettype($_GET['id'])." was passed
\n"; } function isNumeric($numeric) { return preg_match("/^[0-9]+$/", $numeric); }


回答7:

I take a slightly more paranoid approach to sanitizing GET input

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

Code from: http://libox.net



文章来源: php validate integer
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!