Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Input security with "(int)" in PHP?

Tags:

security

php

int

Is (int)$_POST['post_id'] really safe? Won't it allow negative integers?

like image 512
ilhan Avatar asked Dec 25 '10 03:12

ilhan


2 Answers

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']);
like image 111
mikikg Avatar answered Nov 08 '22 18:11

mikikg


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();.

like image 32
deceze Avatar answered Nov 08 '22 18:11

deceze