PHP eval()的错误消息评估系统 [英] error message evaluation system with PHP eval()
问题描述
我正在尝试一个错误消息评估系统,但是我无法使其正常工作以能够评估该系统.
I'm trying out a error message evaluation system but I havn't been able to get it to work to acctually be able to evaluate the system.
您能看到问题在哪里吗?
Can you see what is wrong with it?
$errors = array();
$name = '9';
$familyname = 'family';
$user = '9user`';
$postdata = array('name' => $name,'familyname' => $familyname,'user' => $user);
foreach($postdata as $key => $value)
{
switch($key)
{
case 'name':
$rules = array
(
'strlen($value)>1;' => 'Your name is too short.',
'is_numeric(substr($value,0,1));' => 'Your name has to begin with a character.',
'has_specchar($value);' => 'Your name contains illegal characters.'
);
foreach($rules as $rule => $error)
{
if(eval($rule)) $errors[] = $error;
}
break;
case 'familyname':
break;
case 'user':
$rules = array
(
'strlen($value)<5;' => 'The username is too short.',
'is_numeric(substr($value,0,1));' => 'The username has to begin with a character.',
'has_specchar($value);' => 'The username contains illegal characters.'
);
foreach($rules as $rule => $error)
{
if(eval($rule))
// if(eval($rule)==1)
// if(eval($rule)===1)
// if(eval($rule)==true)
// if(eval($rule)===true)
// None of these have had an effect??!
{
$errors[] = $error;
}
}
break;
default:
}
}
print_r($errors);
function has_specchar($x,$excludes=array())
{
if(is_array($excludes)&&!empty($excludes))
{
foreach($excludes as $exclude)
{
$x=str_replace($exclude,'',$x);
}
}
if(preg_match('/[^a-z0-9 ]+/i',$x))
{
return true;
}
return false;
}
即使我输入了我知道的 SHOULD 触发它成为错误的数据,该错误数组仍为空?!
This error array is empty even though I've entered data I know SHOULD trigger it to become an error??!
推荐答案
来自PHP文档:
除非在评估代码中调用return,否则eval()返回NULL,在这种情况下,将返回传递给return的值.从PHP 7开始,如果所评估的代码中存在解析错误,则eval()会引发ParseError异常.在PHP 7之前,在这种情况下,eval()返回FALSE,并且以下代码的执行正常进行.使用set_error_handler()无法在eval()中捕获解析错误.
eval() returns NULL unless return is called in the evaluated code, in which case the value passed to return is returned. As of PHP 7, if there is a parse error in the evaluated code, eval() throws a ParseError exception. Before PHP 7, in this case eval() returned FALSE and execution of the following code continued normally. It is not possible to catch a parse error in eval() using set_error_handler().
http://php.net/manual/en/function.eval.php
在规则键中添加return
似乎可以解决问题.
Adding return
to your rules keys seems to fix the problem.
$rules = array
(
'return strlen($value)>1;' => 'Your name is too short.',
'return is_numeric(substr($value,0,1));' => 'Your name has to begin with a character.',
'return has_specchar($value);' => 'Your name contains illegal characters.'
);
这篇关于PHP eval()的错误消息评估系统的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!