我有一个PHP脚本接收多个数据(+30)的POST,所有这些都是必需的。如果我能以某种方式捕捉到通知错误“未定义的索引”,而不是像建议的那样使用isset()和strlen()逐个检查,here将是非常好的。在谷歌上搜索,我发现很少有关于这个主题的旧文章,比如this one,所以也许有一些新的技术或变通方法来归档这个目标。
更新:
基于@bishop的回答,以下是我的解决方案:
try {
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$flds = ['data1', 'data2', 'data3'];
if (count(array_diff($flds, array_keys($_POST))) > 0) {
throw new Exception('Missing fields detected!');
}
/* @bishop solution
$vals = array_filter($_POST, function($val) { return ($val != ''); });
if (count(array_diff($_POST, $vals)) > 0) {
throw new Exception('Empty fields detected!');
}
*/
// I prefered using the bellow approach instead of @bishop
// solution, once I will need to sanitize values anyway
foreach($_POST as $input => $value) {
$_POST[$input] = trim($value);
if (strlen($_POST[$input]) === 0) {
throw new Exception('Empty fields detected!');
}
//$_POST[$input] = mysqli_real_escape_string($conn, $value);
}
}
} catch (Exception $e) {
echo $e->getMessage();
}
发布于 2018-04-28 03:24:36
如果要检查每个字段是否都存在,可以使用array_diff和array_filter
// check for missing keys in the post data
$expect = [ 'data1', 'data2', 'data3' ];
if ($missing = array_diff($expect, array_keys($_POST))) {
var_dump($missing);
}
// check for missing values in the post data: modify to suit
$passed = array_filter($_POST, function($value) { return ! empty($value); });
if ($invalid = array_diff($_POST, $passed)) {
var_dump($invalid);
}
但是,要按照您所描述的方式完成此操作:
// temporarily catch all raised errors, warnings, and notices
$errors = [];
set_error_handler(function ($code, $message, $file, $line, $context) use (&$errors) {
$errors[] = [ $code, $message ];
});
// do your "validation"
if ($foo) {
echo "foo";
}
// restore the state of the world, and check for errors
restore_error_handler();
if (count($errors)) {
echo 'Bad bad!';
}
不过,使用风险自负。一般来说,最好是积极地检查接受的值,并使用任何生成的错误/警告/通知作为上下文,以解释逻辑无法按预期工作的原因。
捕获错误以进行检查是许多框架的一部分。一些外部库也提供了它,比如Haldayne/fox。免责声明:我是Haldayne的作者。
https://stackoverflow.com/questions/50068956
复制相似问题