验证码验证表单中的帖子


captcha validating post in form

我只想知道我应该放什么才能猜测验证码在我的 $_POST 中是否错误(验证码图像在我的表单中工作正常),所以我的问题是如何放置错误如果用户在我的验证码图像中输入错误的验证码?

if ($_POST['captcha'] !== $_POST['real']) {
    $errors[] = 'You're wrong';
}

这是我的验证码

session_start();
function random($length) {
    $chars = "abcdefghijklmnopqrstuvwxyz23456789";
    $str = "";
    $size = strlen($chars);
    for ($i=0;$i<$length;$i++) {
        $str .=$chars [rand (0, $size-1)];
    }
    return $str;
}
$cap = random(7);
$_SESSION['real'] = $cap;
$image = imagecreate(100, 20);
$background = imagecolorallocate ($image, 0,0,0);
$foreground = imagecolorallocate ($image, 255,255,255);
imagestring($image, 5,5,1,$cap,$foreground);
header("Content-type: image/jpeg") ;
imagejpeg ($image);

你的形象非常清晰。 易于人类阅读。 对于机器人来说也很容易阅读。 我测试了您的代码并将图像通过一个简单的在线OCR(http://www.i2ocr.com/),它完美地返回了测试。

自己试试吧。

我会考虑使用现有的验证码库。例如谷歌验证码选项。 我喜欢没有验证码重新验证码 ( http://googleonlinesecurity.blogspot.com/2014/12/are-you-robot-introducing-no-captcha.html )

---编辑以回答此案例。

在您的验证码处理文件中

session_start();
$errors[]=array();
if ($_POST['captcha'] != $_SESSION['real']) {
    $errors[] = 'Sorry.  Incorrect Response.  Please Try Again';
}
if(count($errors)>0){
//show user the errors
  print_r($errors);  //You should make this pretty
//probably go back to the login form
echo'<a href="loginform.php">Go Back and Try Again</a>';
//stop processing
exit();
)
//if we got here then the posted captcha matche the 'real' session variable.
echo'Yay!  You got it right!';