captcha.php 代码:
<?php
session_start();
$width = 100;
$height = 40;
// 创建图像
$image = imagecreatetruecolor($width, $height);
// 白色背景
$bgcolor = imagecolorallocate($image, 255, 255, 255);
imagefill($image, 0, 0, $bgcolor);
$captch_code = '';
// 随机生成4位字母、数字组合
for ($i=0; $i < 4; $i++) {
$fontsize = 8;
$fontcolor = imagecolorallocate($image, mt_rand(0,120), mt_rand(0,120), mt_rand(0,120));
$data = 'abcdefghjkmnpqrstvwxyz23456789';
$fontcontent = substr($data, mt_rand(0, strlen($data)), 1);
$captch_code .= $fontcontent;
$x = ($i*100 / 4) + mt_rand(5, 10);
$y = mt_rand(5, 10);
imagestring($image, $fontsize, $x, $y, $fontcontent, $fontcolor);
}
$_SESSION['authcode'] = $captch_code;
// 生成干扰点
for ($i=0; $i < 200; $i++) {
$pointcolor = imagecolorallocate($image, mt_rand(50,200), mt_rand(50,200), mt_rand(50,200));
imagesetpixel($image, mt_rand(1,99), mt_rand(1,39), $pointcolor);
}
// 生成干扰线
for ($i=0; $i < 3; $i++) {
$linecolor = imagecolorallocate($image, mt_rand(80,220), mt_rand(80,220), mt_rand(80,220));
imageline($image, mt_rand(1,99), mt_rand(1,39), mt_rand(1,99), mt_rand(1,39), $linecolor);
}
header('Content-Type:image/png');
imagepng($image);
// 及时销毁图像
imagedestroy($image);form.php 代码:
<?phpif (isset($REQUEST['authcode'])) {
session_start();
if (strtolower($_REQUEST['authcode']) == $_SESSION['authcode']) {
echo '输入正确!';
} else {
echo '输入错误,请返回重试。';
}
exit();
}?><!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<form method="post" action="form.php">
<img id="captcha_img" src="captcha.php?r=<?php echo rand();?>" width="100" height="40" alt="">
<p><a href="javascript:void(0)" onclick="document.getElementById('captcha_img').src='captcha.php?r='+Math.random()">看不清?换一张</a></p>
<input type="text" name="authcode" value="" placeholder="请输入图片中的内容">
<input type="submit" value="提交">
</form>
</body>
</html>from.php
第一行变量输入错误,应该是:$_REQUEST。