t212.php
<html>
<head>
<title>验证码生成与验证</title>
<script type="text/javascript">
function change1() {
var change = document.getElementById("change");
var img = document.getElementById("code_img");
img.src = "./t213.php?t="+ new Date();
}
</script>
</head>
<body>
<form action="./t212.php" method="post">
<p>用户名:<input type="text" name="user_name" value=""></p>
<p>密码:<input type="password" name="password" value=""></p>
<p>验证码:<input type="text" name="captcha"><img id="code_img" src="./t213.php"><a href="#" onclick="change1();">看不清,换一张</a></p>
<p><input type="submit" name="login" value="登录" style="width: 180px;"></p>
</form>
</body>
</html>
<?php
//case 25 验证码生成与验证
@session_start();
//登录按钮
if(isset($_POST['login']))
{
//输入的验证码
$code = isset($_POST['captcha'])?trim($_POST['captcha']):'';
if(!isset($_SESSION['captcha_code'])) die('验证码已过期,请重新登录');
echo "code=$code"."<br>";
echo "session =".$_SESSION['captcha_code']."<br>";
//小写比较
if(strtolower($code) == strtolower($_SESSION['captcha_code']))
{
echo "验证码正确";
}
else
{
echo "验证码输入错误";
}
session_destroy();
}
?>
t213.php
<?php
//图片宽度
$img_width = 80;
//图片高度
$img_height = 26;
//字符数
$char_len = 5;
//字体大小
$font = 5;
//字典数组
$char = array_merge(range('A','Z'),range('a','z'),range(1,9));
//数组随机取5个字符
$rand_keys = array_rand($char,$char_len);
//
if($char_len == 1)
{
$rand_keys = array($rand_keys);
}
//打乱数组
shuffle($rand_keys);
$code = '';
//串联字符
foreach ($rand_keys as $key)
{
$code .= $char[$key];
}
@session_start();
//保存至会话
$_SESSION['captcha_code'] = $code;
//创建画布
$img = imagecreatetruecolor($img_width,$img_height);
//背景颜色
$bg_color = imagecolorallocate($img,0xcc,0xcc,0xcc);
//填充背景色
imagefill($img,0,0,$bg_color);
//干扰点
for ($i=0; $i<=300;$i++)
{
//随机颜色
$color = imagecolorallocate($img,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255));
//随机像素点
imagesetpixel($img,mt_rand(0,$img_width),mt_rand(0,$img_height),$color);
}
//边框颜色
$rect_color = imagecolorallocate($img,0xff,0xff,0xff);
//画边框
imagerectangle($img,0,0,$img_width-1,$img_height-1,$rect_color);
//字符串颜色
$str_color = imagecolorallocate($img,mt_rand(0,100),mt_rand(0,100),mt_rand(0,100));
//单字体宽度
$font_width = imagefontwidth($font);
//单字体高度
$font_height = imagefontheight($font);
//字符串宽度
$str_width = $font_width * $char_len;
//形成字符串
imagestring($img,$font,($img_width-$str_width)/2,($img_height-$font_height)/2,$code,$str_color);
header('Content-type:image/png');
//保存图片
imagepng($img);
//内存清除
imagedestroy($img);