让PHP停止替换"。" $ _GET或者$ _POST数组中的字符?
时间:2020-03-05 18:54:59 来源:igfitidea点击:
如果我通过$ _GET传递名称中带有.
的PHP变量,PHP会自动将其替换为_
字符。例如:
<?php echo "url is ".$_SERVER['REQUEST_URI']."<p>"; echo "x.y is ".$_GET['x.y'].".<p>"; echo "x_y is ".$_GET['x_y'].".<p>";
...输出以下内容:
url is /SpShipTool/php/testGetUrl.php?x.y=a.b x.y is . x_y is a.b.
...我的问题是这样:我有什么办法可以阻止这种情况发生?无法为我的一生弄清我应做的一切
我运行的PHP版本是5.2.4-2ubuntu5.3.
解决方案
回答
发生这种情况的原因是由于PHP的旧register_globals功能。这 。 character不是变量名称中的有效字符,因此PHP会将其隐藏在下划线中,以确保兼容性。
简而言之,在URL变量中加句点不是一个好习惯。
回答
这是PHP.net对其执行原因的解释:
Dots in incoming variable names Typically, PHP does not alter the names of variables when they are passed into a script. However, it should be noted that the dot (period, full stop) is not a valid character in a PHP variable name. For the reason, look at it: <?php $varname.ext; /* invalid variable name */ ?> Now, what the parser sees is a variable named $varname, followed by the string concatenation operator, followed by the barestring (i.e. unquoted string which doesn't match any known key or reserved words) 'ext'. Obviously, this doesn't have the intended result. For this reason, it is important to note that PHP will automatically replace any dots in incoming variable names with underscores.
那是来自http://ca.php.net/variables.external。
另外,根据此注释,这些其他字符也将转换为下划线:
The full list of field-name characters that PHP converts to _ (underscore) is the following (not just dot): chr(32) ( ) (space) chr(46) (.) (dot) chr(91) ([) (open square bracket) chr(128) - chr(159) (various)
因此,看起来好像我们坚持使用它,因此我们必须使用awnerd的建议将下划线转换回脚本中的点(不过我只是使用str_replace。)
回答
回答时间长的问题,但实际上有更好的答案(或者解决方法)。 PHP使我们可以进入原始输入流,因此可以执行以下操作:
$query_string = file_get_contents('php://input');
这将为我们提供查询字符串格式的$ _POST数组,其句点应为应有的句点。
然后,我们可以根据需要对其进行解析(根据POSTer的评论)
<?php // Function to fix up PHP's messing up input containing dots, etc. // `$source` can be either 'POST' or 'GET' function getRealInput($source) { $pairs = explode("&", $source == 'POST' ? file_get_contents("php://input") : $_SERVER['QUERY_STRING']); $vars = array(); foreach ($pairs as $pair) { $nv = explode("=", $pair); $name = urldecode($nv[0]); $value = urldecode($nv[1]); $vars[$name] = $value; } return $vars; } // Wrapper functions specifically for GET and POST: function getRealGET() { return getRealInput('GET'); } function getRealPOST() { return getRealInput('POST'); } ?>
对于同时包含两个'。'的OpenID参数非常有用。和" _",每个都有特定含义!