关于复合语句的PHP(int)

时间:2017-01-30 21:07:34

标签: php int

这令我感到意外。代码

$strA = '1234';
$strB = '56';
$cast = (int) $strA.$strB;
var_dump($cast);

输出:字符串(6)“123456”

我期待$ cast为整数。如果有人将$ _POST中的字符串放在一起,则此行为可能会导致安全漏洞。代码

$strA = '1234';
$strB = '56-SQL Injection';
$cast = (int) $strA.$strB;

输出:string(20)“123456-SQL Injection”

如果$ strB来自外部来源,如$ _POST;该脚本可能对注入攻击开放。

我一直在阅读像difference between (int) and intval()这样的帖子,试图找出(int)的完整行为记录在哪里。

所以我的问题是:我期待“(int)$ strA。$ strB”是一个整数。为什么它仍然是一个字符串,这个行为记录在哪里?

1 个答案:

答案 0 :(得分:1)

行为是由运营商优先级引起的,另请参阅相应的manual page

基本上是:

(int) $a.$b;

不同
(int) ($a.$b); //which is the one you want

但与

相同
((int) $a).$b;

在你的情况下,将$ a转换为有效的int,然后将其隐含地转换为字符串以与$ b连接。
(对于非数字字符串,例如$a="b",这将导致最终字符串"0456"

请参阅此示例输出:

<?php
$a = "123";
$b = "456";
$c = (int) $a.$b;
$d = (int) ($a.$b);
$e = ((int) $a).$b;
var_dump($c, $d, $e);
  

string'123456'(长度= 6)
  int 123456
  字符串'123456'(长度= 6)

另外:除非你绝对不能,否则总是使用参数化语句来阻止SQL注入 - 它们尽可能接近万无一失。