PHP-自动处理每个$ _POST变量是否会成为安全问题? [英] PHP - Could automatically processing every $_POST variable be a security issue?

查看:175
本文介绍了PHP-自动处理每个$ _POST变量是否会成为安全问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

场景:我的PHP脚本需要10个POST字符串才能工作.所有它们的值都需要使用htmlspecialchars()进行转义.因此,脚本的第一行如下所示:

Scenario: My PHP script requires 10 POST strings to work. The value of all of them needs to be escaped with htmlspecialchars(). So the first lines of the script look like this:

$var1 = htmlspecialchars($_POST['var1']);
$var2 = htmlspecialchars($_POST['var2']);
// And more. You get the point.

这是一些可以简化它的代码:

This is some code that could simplify it:

foreach($_POST as $key => $value){
    $$key = htmlspecialchars($_POST[$value]);
}

我不确定用户输入的$$.我猜有人可以发送许多我不需要的POST请求,并以此阻止服务器.这是现实的吗?

I'm unsure about the $$ with user input. I guess somebody could send many POST requests I don't need and block the server with that. Is this realistic?

foreach代码将在我脚本的最顶部.因此它将无法覆盖其他任何变量.

The foreach code would be at the very top of my script. So it won't be able to overwrite any other variables.

推荐答案

除了只盲目地处理$_POST中的所有内容(尽管只是将它们通过htmlspecialchars()传递是相当无害的),您还可以使用密钥白名单可以接受:

Rather than just blindly handling everything in $_POST (although just passing them through htmlspecialchars() is pretty harmless), you can use a whitelist of keys that are acceptable:

// An array of $_POST keys that are acceptable
$whitelist = array('var1','var2','var3');

foreach($_POST as $key => $value) {
   // Only handle $_POST keys you expect to receive...
   if (in_array($key, $whitelist)) {
      $$key = htmlspecialchars($_POST[$value]);
    }
}

这避免了恶意用户向POST提交数百个值并消耗额外的系统资源的可能性.

This evades the possibility of a malicious user submitting hundreds of values to POST and consuming extra system resources.

注释者是正确的.遍历白名单比$_POST更好:

Commenters are correct. It is better to iterate through the whitelist than $_POST:

// Iterate over $whitelist and check for corresponding keys in $_POST
$missing_keys = array();
foreach($whitelist as $key) {
   if (isset($_POST[$key])) {
     $$key = htmlspecialchars($_POST[$key]);
   }
   else $missing_keys[] = $key;
}
echo "Missing keys: " . implode(",", $missing_keys);

这篇关于PHP-自动处理每个$ _POST变量是否会成为安全问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆