2

什么是清理用户输入的最有效方法是完全由数字组成的逗号分隔字符串 - 例如

2,40,23,11,55

我在很多输入上都使用了这个功能

function clean($input){ $input=mysql_real_escape_string(htmlentities($input,ENT_QUOTES)); return $input; }

在简单的整数上,我这样做:

if (!filter_var($_POST['var'], FILTER_VALIDATE_INT)) {echo('error - bla bla'); exit;}

所以我应该把它分解然后用上面的代码检查数组的每个元素,或者用''替换所有出现的','然后检查整个东西是一个数字吗?你们有什么感想?

4

4 回答 4

3
if (ctype_digit(str_replace(",", "", $input))) {
  //all ok. very strict. input can only contain numbers and commas. not even spaces
} else {
  //not ok
}

如果它是 CSV,并且数字或逗号周围可能有空格,甚至一些引号最好使用正则表达式来检查它是否匹配

于 2009-11-17T16:30:27.130 回答
2
if (!preg_match('/\A\d+(,\d+)*\z/', $input)) die('bad input');
于 2009-11-17T16:31:31.220 回答
0

如果你想转换一个逗号分隔的列表,而不是简单地拒绝它,如果它没有正确形成,你可以这样做array_map()并避免编写显式循环。

$sanitized_input = implode(",", array_map("intval", explode(",", $input)));
于 2009-11-17T17:02:48.477 回答
0

我会过滤而不是对简单输入进行错误检查,尽管只是因为我很懒,我想,而且通常在网络环境中,有太多的情况需要处理我没想到的情况:简单下面筛选。

<?php
$input = '234kljsalkdfj234a,a, asldkfja 345345sd,f jasld,f234l2342323@#$@#';
function clean($dirty){ // Essentially allows numbers and commas, just strips everything else.
    return preg_replace('/[^0-9,]/', "", (string) $dirty);
}

$clean = clean($input);

echo $clean;
// Result: 234234,,345345,,2342342323
// Note how it doesn't deal with adjacent filtered-to-empty commas, though you could handle those in the explode.  *shrugs*

?>

这是键盘上的代码和输出:

http://codepad.org/YfSenm9k

于 2009-11-17T17:19:55.580 回答