【发布时间】:2017-03-20 13:09:55
【问题描述】:
我正在尝试一个错误消息评估系统,但我无法让它真正能够评估系统。
你能看出它有什么问题吗?
$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;
}
这个错误数组是空的,即使我输入了我知道应该触发它变成错误的数据??!
【问题讨论】:
-
这种方法是一种非常奇特的方法,已经被遵循了数百万次并且总是被证明是一个坏主意。不将代码存储在字符串中。它效率低下,不安全,没有必要这样做。代码和文本是两个不同的东西。不要混合它们。
-
arkascha,你知道我想要完成什么。您对如何更好地处理这种情况有什么建议吗?就像我说的。我很高兴收到反馈。
-
不要试图以某种方式“抽象”那些规则集。用保守的条件对它们进行编码,这样更健壮。如果你真的坚持这么花哨的东西,那么使用动态函数或 lambdas,但不要使用
eval()。