PHP验证码不起作用


php captcha code not working

我正在使用一个旧的random()函数为我在网络上找到的AJAX注释系统创建验证代码(源代码在LINK)。

背后的想法非常简单:

 function Random()
{
$chars = "ABCDEFGHJKLMNPQRSTUVWZYZ23456789";
srand((double)microtime()*1000000);
$i = 0;
$pass = '' ;
while ($i <= 4)
{
$num = rand() % 32;
$tmp = substr($chars, $num, 1);
$pass = $pass . $tmp;
$i++;
}
return $pass;
}
$random_code = Random(); 

然后在表单中,就在"提交"按钮之前:

<label for="security_code">Enter this captcha code: <b><? echo $random_code; ?></b></label>
<input type="text" name="security_code" id="security_code" />
<input name="randomness" type="hidden" id="randomness" value="<?php $random_code; ?>"> 

我的 AJAX 注释系统使用这样的东西来检查字段是否为空(即是否有任何错误):

$errors = array();
$data= array();
[...]
if(!($data['name'] = filter_input(INPUT_POST,'name',FILTER_CALLBACK,array('options'=>'Comment::validate_text'))))
{
$errors['name'] = 'Please enter a name.';
}
if(!empty($errors)){
[...]
}

所以我写了这个:

if(!($data['security_code'] = filter_input(INPUT_POST,'security_code',FILTER_CALLBACK,array('options'=>'Comment::validate_text'))))
{
$errors['security_code'] = 'You did not enter the validation code.';
}
elseif(!($data['security_code'] = $randomness))
{
$errors['security_code'] = 'You entered the validation code incorrectly. Please note that it is case sensitive.';
} 

但是,当我在验证代码文本字段中插入随机文本后单击"提交"按钮(在LINK上自己测试)时,我总是收到"您输入的验证代码不正确"消息。

print_r($_POST) 给出一个空数组,然后在我单击提交后脚本挂起:数组()

我错过了什么?原始验证码在验证过程中的某个时刻丢失(第 3 和第 4 个代码块)。提前致谢

在这里看到你的代码后,我看到静态函数 validate 不知道变量$randomness!从您的提交.php中,您正在进行以下调用:

$arr = array();
$validates = Comment::validate($arr);

函数validate对变量$randomness一无所知,除非你把这样的东西传递给它 - 它在不同的范围内。

尝试修改上面提到的代码:

    $arr = array(); // no change here  
    $randomness = isset($_POST['randomness']) ? $_POST['randomness'] : '';   
    // Check for empty randomness before you validate it in Comment::validate
    // so that you donot verify for '' == '' there. 
    $validates = Comment::validate($arr, $randomness);

并按如下方式更改验证函数:

    public static function validate(&$arr, $randomness)
    {

我知道这不是优雅的解决方案 - 那需要你自己学到更多的东西,这只是为了给你指路......
让我知道它是怎么回事。

而不是:

<input name="randomness" type="hidden" id="randomness" value="<?php $random_code; ?>"> 

写:

<input name="randomness" type="hidden" id="randomness" value="<?php echo $random_code; ?>"> 

也代替:

elseif(!($data['security_code'] = $randomness))
{
$errors['security_code'] = 'You entered the validation code incorrectly. Please note that it is case sensitive.';
}

也许这个:

elseif($data['security_code'] != $randomness) {
   $errors['security_code'] = 'You entered the validation code incorrectly. Please note that it is case sensitive.';
} 

另外,$data从哪里获得其价值?_POST美元,_GET美元print_r()它,也点亮$_REQUEST