前端代码(login.php):
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div>
<form method='post' action='check_login.php'>
<table>
<tr>
<td>用户名:</td>
<td><input type="text" size="22" name="username" />
</td>
</tr>
<tr>
<td>密码:</td>
<td><input type="password" size="22" name="passwd" /></td>
</tr>
<tr>
<td>验证码:</td>
<td><input style="display:inline-block;float:left;" type="text" name="yanzhenma" size=4/>
<img style="display:inline-block;float:left;width:110px;height:23px;" src="demo2.php" onclick="this.src='demo2.php?id='+Math.random()"/>
</td>
</tr>
<tr>
<td colspan="2">
<input id="login" type="submit" value="登录" />
</td>
</tr>
</table>
</form>
</div>
</body>
</html>
图:
php验证码代码(demo2.php):
<?php
$str = '1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM';
//打乱字符串
$strNew = str_shuffle($str);
//截取字符串前4个字符
$content = substr($strNew,0,4);
//保存截取到的字符串
session_start();
$_SESSION['char'] = $content;
//创建画布,宽100,高28
$i = imagecreatetruecolor(100,28);
//设置画布背景颜色,红绿蓝随机数为100到255,组成浅色
$bgcolor = imagecolorallocate($i,mt_rand(100,255),mt_rand(100,255),mt_rand(100,255));
//给画布设置背景颜色(0,0)为设置颜色的开始坐标
imagefill($i,0,0,$bgcolor);
//加入干扰项
for($num=0;$num<100;$num++){
//画100个随机的点
$color = imagecolorallocate($i,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255));//设置随机的颜色
imagesetpixel($i,mt_rand(0,100),mt_rand(0,100),$color);//在随机>的坐标画点
}
for($num=0;$num<3;$num++){
//画3条线
$color = imagecolorallocate($i,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255));//线的颜色随机
imageline($i,0,mt_rand(0,28),100,mt_rand(0,28),$color);//线的位>置为随机,开始坐标为(0,随机数0~28),结束位置为(100.随机数0~28)
}
//写验证码
for($index=0;$index<strlen($content);$index++){
//循环写入数字
$char = $content[$index];//获取截取到的4个验证码字符
$x = 15+20*$index;//设置验证码中字符的位置
$color = imagecolorallocate($i,mt_rand(0,155),mt_rand(0,155),mt_rand(0,155));//设置验证码中字符的颜色为随机数
imagefttext($i,16,mt_rand(-15,15),$x,22,$color,'./STKAITI.TTF',$char);//写入验证码字符,字体大小16,倾斜角度为-15到15,x坐标为不同的4个位置,y坐
标为22,字体为华文字体,写的字是字符串截取到的4个数字字母
}
header("content-type:image/png");
imagepng($i);
?>
图:
php验证表单,验证码是否填写正确(check_login.php):
<?php
session_start();//开启session对话,必须在html前
//post方法获取表单用户名,密码
$username = $_POST['username'];
$passwd = $_POST['passwd'];
$yanzhenma = $_POST['yanzhenma'];
$char = $_SESSION['char'];
if($yanzhenma == $char){
echo 'ok';
}else{
echo 'error';
}
?>