带有 PHP eval() 的错误消息评估系统



我正在尝试一个错误消息评估系统,但我无法让它工作以最终能够评估系统。

你能看出它有什么问题吗?

$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;
}

即使我输入了我知道应该触发它成为错误的数据,此错误数组也是空的??!

来自 PHP 文档:

eval() 返回 NULL,除非在计算的代码中调用 return,在这种情况下,将返回传递给 return 的值。从 PHP 7 开始,如果评估的代码中存在解析错误,eval() 会抛出 ParseError 异常。在 PHP 7 之前,在这种情况下,eval() 返回 FALSE,并且以下代码的执行继续正常。使用 set_error_handler() 无法在 eval() 中捕获解析错误。

http://php.net/manual/en/function.eval.php

return添加到规则键似乎可以解决问题。

$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.'
);

相关内容

最新更新