使用“(int)”输入安全性在 PHP 中?
(int)$_POST['post_id']
真的安全吗?它不允许负整数吗?
Is (int)$_POST['post_id']
really safe? Won't it allow negative integers?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
假设您的意思是在 SQL 注入或 XSS 攻击方面“安全”,那么“可能”是的。转换为
int
仅确保该值是整数。整数在任何情况下通常都不危险。但它不能保证整数值的安全。它可能是0
,在您的代码中可能有也可能没有特殊含义,例如与false
进行比较时。或者它可能是负面的,这同样可能会或可能不会对您的代码产生任何副作用。“安全”并不是绝对的。字符串“1 = 1; DROP TABLE users”本身也非常安全。这仅取决于您使用它的上下文。同样,
0
是完全安全的,直到您的代码包含if (!$number) deleteAllUsers();
。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 be0
, which may or may not have a special meaning in your code, for example when comparing tofalse
. 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, a0
is perfectly safe until your code includesif (!$number) deleteAllUsers();
.它是“安全的”,取决于你想做什么。就
PHP
的内存使用而言,它只会将变量转换为整数。它将允许负整数。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.对于 PHP 中的 (int):
切勿将未知分数转换为整数,因为这有时会导致意外结果。
查看有关整数的 PHP 文档。
For (int) in PHP:
Never cast an unknown fraction to an integer, as this can sometimes lead to unexpected results.
Check out the PHP documentation on integers.
int
的使用用于类型hinting转换,就像对于负整数是安全的
我的错误:类型提示仅适用于数组和对象
有关类型转换的更多详细信息
The use of
int
is for typehintingcasting, likeis safe for negative integers
my mistake: type hinting only applicable for array and object
more details on type casting
是的,就 SQL 注入或 XSS 攻击而言,它是“安全的”。
此外,如果您对数据库中的主键或其他字段使用无符号整数(无负值)(节省空间),则需要使用 PHP 函数 abs() 和强制转换来防止未处理的错误:
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: