如果要清理 中的所有元素$_POST
,则可以创建一个清理函数并将其应用于所有元素array_map
:
$post_clean = array_map("sanitization_function", $_POST);
然后你会通过$post_clean
而不是访问你的变量$_POST
。
它看起来像:
function sanitize($dirty){
return preg_replace( "/[^a-zA-Z0-9_]/", "", $dirty );
}
$cPOST = array_map("sanitize", $_POST);
if (!strlen($cPOST['username'])){
die("username is blank!");
}
如果您只想清理$_POST
元素的子集,您可以执行以下操作:
$cPOST = array();
$sanitize_keys = array('username','someotherkeytosanitize');
foreach($_POST as $k=>$v)
{
if(in_array($k, $sanitize_keys))
{
$cPOST[$k] = preg_replace( "/[^a-zA-Z0-9_]/", "", $v);
}
else
{
$cPOST[$k] = $v;
}
}
尝试这个:
$cPOST = array();
$sanitize_keys = array('username','someotherkeytosanitize');
for($_POST as $k=>$v)
{
if(in_array($k, $sanitize_keys))
{
$cPOST[$k] = preg_replace( "/[^a-zA-Z0-9_]/", "", $v);
if(strlen($cPOST[$k]) == 0){
die("%s is blank", $k);
}
}
else
{
$cPOST[$k] = $v;
}
}
# At this point, the variables in $cPOST are the same as $_POST, unless you
# specified they be sanitized (by including them in the $sanitize_keys array.
# Also, if you get here, you know that the entries $cPOST that correspond
# to the keys in $sanitize_keys were not blank after sanitization.
只需确保将 $sanitize_keys 更改为您想要清理的任何变量(或 $_POST 键)的数组。