场景:我的PHP脚本需要10个POST字符串才能工作.所有这些的价值都需要转义htmlspecialchars().所以脚本的第一行看起来像这样:
$var1 = htmlspecialchars($_POST['var1']);
$var2 = htmlspecialchars($_POST['var2']);
// And more. You get the point.
Run Code Online (Sandbox Code Playgroud)
这是一些可以简化它的代码:
foreach($_POST as $key => $value){
$$key = htmlspecialchars($_POST[$value]);
}
Run Code Online (Sandbox Code Playgroud)
我不确定$$用户输入.我想有人可以发送我不需要的许多POST请求并用它阻止服务器.这是现实的吗?
该foreach代码将在我的脚本的最顶端.所以它将无法覆盖任何其他变量.
而不是盲目地处理所有内容$_POST(虽然只是通过它们htmlspecialchars()是非常无害的),您可以使用可接受的密钥白名单:
// 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]);
}
}
Run Code Online (Sandbox Code Playgroud)
这避免了恶意用户向POST提交数百个值并消耗额外系统资源的可能性.
评论者是对的.迭代白名单最好是$_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);
Run Code Online (Sandbox Code Playgroud)