Is (int)$_POST['post_id']
really safe? Won't it allow negative integers?
Assuming you mean safe in terms of SQL injection or XSS attacks, then probably yes. Casting to an int
only makes sure the value is an integer. An integer is not usually dangerous in any context. It does not guarantee the safety of the integer's value though. It may be 0
, which may or may not have a special meaning in your code, for example when comparing to false
. Or it may be negative, which, again, may or may not have any side effects in your code.
"Safety" isn't an absolute thing. The string "1 = 1; DROP TABLE users"
by itself is pretty safe, too. It just depends on the context you're using it in. Just the same, a 0
is perfectly safe until your code includes if (!$number) deleteAllUsers();
.
It is "safe", depending on what you want to do. It will only cast the variable to an integer as far as PHP
s memory usage is concerned. It will allow negative integers.
The use of int
is for type hinting casting, like
php -r "var_dump( (int) '123d');"
>>> int(123)
php -r "var_dump( (int) '-123d');"
>>> int(-123)
php -r "var_dump( (int) '<script>alert(false)</script>');"
>>> int(0) (xss, no problem)
is safe for negative integers
my mistake: type hinting only applicable for array and object
For (int) in PHP:
decimal : [1-9][0-9]*
| 0
hexadecimal : 0[xX][0-9a-fA-F]+
octal : 0[0-7]+
binary : 0b[01]+
integer : [+-]?decimal
| [+-]?hexadecimal
| [+-]?octal
| [+-]?binary
Never cast an unknown fraction to an integer, as this can sometimes lead to unexpected results.
Check out the PHP documentation on integers.
Yes, it is "safe" in terms of SQL injection or XSS attacks.
In addition, if you utilize unsigned integers (no negative values) for primary keys or other fields in your database (save space) you need to use PHP function abs() and casting to prevent unhandled errors:
$safe_int = abs((int)$_POST['post_id']);