我尝试实现php图像验证码,这里是test.php
文件:
<form method="POST" action="processor.php">
<div style="float:left;">Code: <input type="text" name="verif_box" style="cursor:text"> </div>
<div style="margin-top:0px;position:relative;left:5px; top:-8px;"><IMG SRC="image.php"></div>
<input type="submit" name="submit" value="Submit">
</FORM>
以下是image.php
:
$width = 60;
$height = 24;
$my_image = imagecreatetruecolor($width, $height);
imagefill($my_image, 0, 0, 0xFFFFFF);
for ($c = 0; $c < 110; $c++){
$x = rand(0,$width-1);
$y = rand(0,$height-1);
imagesetpixel($my_image, $x, $y, 0x000000);
}
$sessioncode=rand(0,9999);
imagestring($my_image, 5, 0, 0, substr(strtoupper(md5("Mytext".$sessioncode)), 0,6), $textcolor);
setcookie('tntcon',(md5("Mytext".$sessioncode)));
imagejpeg($my_image);
imagedestroy($my_image);
exit();
以下是processor.php
:
$verif_box = $_POST["verif_box"];
if (strtoupper($_COOKIE['tntcon']) == strtoupper($verif_box)) {
echo "right code";
} else {
echo "wrong code";
}
问题是,即使我输入了正确的验证码,在processor.php文件中总是给我“错误的代码”消息,我做错了什么?
答案 0 :(得分:3)
您不是在cookie中存储代码,而是存储代码的完整md5-hash。
setcookie('tntcon',(md5("Mytext".$sessioncode)));
只存储Cookie中的前6个字符。
setcookie('tntcon',(strtoupper(substr(md5("Mytext".$sessioncode), 0, 6))));
另一个(更好的)选项是将代码存储在会话中:
//image.php
session_start();
$_SESSION['code'] = strtoupper(substr(md5('Mytext' . $sessioncode), 0, 6));
//processor.php
session_start();
if ($_SESSION['code'] == strtoupper($_POST["verif_box"])) {
// Correct code
} else {
// Incorrect code
unset($_SESSION['code']);
}
答案 1 :(得分:0)
您只在图像中显示6个字符,但将整个md5哈希存储在cookie中。更好的方法是这样:
$captchacode = substr(strtoupper(md5(rand(234,234234))), 2,6);
imagestring($my_image, 5, 0, 0, $captchacode, $textcolor);
setcookie('tntcon', $captchacode);