是(int)$ _ GET ['user_input']安全吗?

问题描述:

Is it safe to assume that in

if (($i = (int)trim($_GET['user_input'])) != 0) {
    // do stuff with $i
}

$i can only ever be an integer?


Edit:

I now use:

if (ctype_digit($i = $_GET['user_input'])) {
    // do stuff with $i
}

假设在 p>

  if(()  $ i =(int)trim($ _ GET ['user_input']))!= 0){
 //用$ i做的东西
} 
  code>  pre> 
 
 

$ i code>只能是一个整数? p>


编辑: strong> p>

我现在使用: p>

  if(ctype_digit($ i = $ _GET ['user_input'])){
 // //用$ i做的东西 n} 
  code>  pre> 
  div>

So if your only question is if it's in any case a int, then is the answer :

Yes

But if the cast to int fails (e.g. input: 'a') $i is just 0

Example:

Input/ Output:

4       ->  4
-5      -> -5
"14"    -> 15
"a"     ->  0
"!"     ->  0
array() ->  0

Side Note:

If the value is an array trim fails and you get an error

Check this

if(stripslashes(trim($_GET['user_input']))) > 0){
//your code Here 
}

$i = intval($_GET['user_input']);
if ( $i != 0) {
    // do stuff with $i
}

check it's documentation here

If you check for integer, then

if(is_numeric($_GET['user_input']) && $_GET['user_input'] > 0) {
//your code
}