首先我们分以下几个步骤:
1.使用php创建一个图像
2.登陆页面引入php创建的图像
3.验证输入的是否正确
这其中最核心的就是用php创建图像,那么接下来就跟着我一起开始吧
首先新建一个captcha.php 文件内容:
<?php
// 设置验证输出的内容,提示:一般剔除数字和字母容易混淆的几个
$data = "abcdefghjklmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ0123456789";
// 创建一个画布,就是验证码的大小
$width = 100;
$height = 30;
$img = imagecreatetruecolor($width,$height);
$color = imagecolorallocate($img,0xcc,0xcc,0xcc);
// 填充颜色 imgefill()
imagefill($img,0,0,$color);
// 绘制画布的噪点 这里假设设置600个噪点
for($i=0;$i<600;$i++)
{
$color = imagecolorallocate($img,rand(0,100),rand(0,100),rand(0,100));
$x = rand(0,$width);
$y = rand(0,$height);
imagesetpixel($img,$x,$y,$color);
}
// 绘制画布的干扰线,这里假设画6道线
for($i = 0; $i<6; $i++)
{
$color = imagecolorallocate($img, rand(100, 200), rand(100, 200), rand(100,200));
$x1 = rand(0, $width);
$y1 = rand(0, $height);
$x2 = rand(0, $width);
$y2 = rand(0, $height);
imageline ($img, $x1, $y1, $x2, $y2, $color);
}
// 绘制圆来干扰 假设画4个圆
for ($i=0; $i<4; $i++)
{
$color = imagecolorallocate ($img, rand(100, 255), rand(100, 255), rand(100,255));
imageellipse ($img, rand(0, $width), rand(0, $height),30,30,$color);
}
/**
* 验证码内容
* $len : 字符串长度
* $ font : 字体的路径,需要自己下载特殊字体
* $captcha: 验证码内容
*/$len = strlen($data);
$font = './font/texb.ttf';
$captcha = ""; // 这一步不能少,不然会出现报错,设置一个空的变量
for ($i = 0; $i<4; $i++)
{
$textcolor = imagecolorallocate ($img, rand(0,100), rand(0,100), rand(0,100));
$index = rande (0, $len-1);
$indexstr = substr ($str, $index, 1);
$captcha. = $indexstr;
$x = 10+$i*20;
$y = 20;
imagettftext ($img, 18 , rand(-50, 50), $x, $y, $textcolor, $font, $indexstr);
}
// 这里开启session
session_start();
// 用session 保存验证码内容
$_SESSION["captcha"] = $captcha;
// 设置格式输出画布
header ('content-type:image/png');
imagepng ($img);
// 最后销毁这个图片
imagedestroy ($img);
?>
2.引入这个文件放到登陆页面或者注册页面,假设同一级目录,加上点击切换事件
<form action="login.php" method ="post">
<label>验证码:</label>
<input type="text" name="captcha">
<img src="captcha.php" onclick = "this.src='captcha.php?nocache='+Math.random()"/>
<input type="submit" value="登陆">
</form>
3.获取接收的验证码进行验证输入的是否正确,login.php 页面验证
<?php
// 设置字符集,避免输出乱码
header ("Content-Type:text/html; charset=utf-8");
if (isset($_POST['captcha'])){
session_start();
if(strtolower($_POST['captcha'])==$_SESSION['captcha']){
echo "验证码输入正确";
} else {
echo "验证码输入错误";
}
exit();
}
?>