如何检查此验证码脚本的正确性

时间:2012-11-22 11:15:12

标签: php captcha

如何在服务器端PHP中检查此验证码脚本的正确性?

我使用此脚本显示验证码图像并通过ajax进行检查。现在我想在服务器端PHP中检查它。怎么做?

captcha.php

<?php
//Start a session so we can store the captcha code as a session variable.
session_start();

// Decide what characters are allowed in our string
// Our captcha will be case-insensitive, and we avoid some
// characters like 'O' and 'l' that could confuse users
$charlist = '23456789ABCDEFGHJKMNPQRSTVWXYZ'; 

// Trim string to desired number of characters - 5, say
$chars = 5;
$i = 0;
while ($i < $chars) 
{ 
  $string .= substr($charlist, mt_rand(0, strlen($charlist)-1), 1);
  $i++;
}

// Create a GD image from our background image file
$captcha = imagecreatefrompng('images/captcha.png');

// Set the colour for our text string
// This is chosen to be hard for machines to read against the background, but
// OK for humans
$col = imagecolorallocate($captcha, 0, 0, 0);

// Write the string on to the image using TTF fonts
imagettftext($captcha, 29, 1, 15, 29, $col, 'images/fonts/arial.ttf', $string);

// Store the random string in a session variable
$_SESSION['secret_string'] = $string;

// Put out the image to the page
header("Content-type: image/png");
imagepng($captcha);
?>

2 个答案:

答案 0 :(得分:0)

当用户提交的表单与$_SESSION['secret_string']匹配发布的代码时,您在$_SESSION['secret_string']中有验证码。

答案 1 :(得分:0)

为了验证服务器端的验证码,您可以

<?php
session_start();
//code is the name of your captcha text field
if($_SESSION['secret_string']==$_POST['code'])
echo "Captcha verfication passed..";
else
echo "Captcha verfication failed..";
?>