Introductory security using "(int)" in PHP?

Is (int)$_POST['post_id'] really safe? Will negative integers be allowed?

+8
security php int
source share
5 answers

Assuming you mean injection-safe SQL or XSS attacks, perhaps yes. Running only int ensures that the value is an integer. An integer is usually not dangerous in any context. However, this does not guarantee the safety of an integer value. It may be 0 , which may or may not have much significance in your code, for example, when comparing with false . Or it may be negative, which again may or may not have any side effects in your code.

"Security" is not an absolute thing. The string "1 = 1; DROP TABLE users" in itself is pretty safe. It depends on the context in which you use it. Similarly, 0 absolutely safe until your code turns on if (!$number) deleteAllUsers(); .

+11
source share

This is "safe", depending on what you want to do. It will only pass the variable to an integer before using PHP memory. It will give negative integers.

+3
source share

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 add an unknown part to an integer, as this can sometimes lead to unexpected results.

Discard the PHP documentation on integers .

+3
source share

Using int for tooltip type e.g.

 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) 

safe for negative integers

my mistake: hinting type is applicable only for array and object

more about casting type

+1
source share

Yes, it is “safe” in terms of SQL injection or XSS attacks.

In addition, if you use unsigned integers (without negative values) for primary keys or other fields in your database (save space), you need to use the PHP abs () function and casting to prevent unhandled errors:

 $safe_int = abs((int)$_POST['post_id']); 
0
source share

Source: https://habr.com/ru/post/650434/


All Articles