完成结果图
1.captcha.class.php生成验证码类文件
<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2019/10/9 0009
* Time: 6:15
*/
class Captcha
{
//定义画布
private $img;
//画布宽
public $width = 100;
//画布高
public $height = 30;
//画布颜色
// public $color = '255';
//随机验证码的长度
public $code_len = 4;
//随机验证码
public $captcha;
//字体大小
public $font_size = 5;
public function __construct()
{
$this->create_img();
$this->create_code();
$this->create_pix();
}
//创建画布
private function create_img(){
$w = $this->width;
$h = $this->height;
$this->img = imagecreatetruecolor($w,$h);
$color = imagecolorallocate($this->img,255,255,255);
imagefill($this->img,0,0,$color);
}
//生成验证码
private function create_code(){
$str = 'abcdefghigklmnopqrstuvwxyz0123456789ABCDDEFGHIGKLMNOPQRSTUVWXYZ';
$code = '';
for ($i=0;$i<$this->code_len;$i++){
$code = substr($str,mt_rand(0,strlen($str)-1),1);
//字的颜色
$color = imagecolorallocate($this->img,mt_rand(0,120),mt_rand(0,120),mt_rand(0,120));
//将字画到花板上
$x = ($this->width/$this->code_len) * $i + mt_rand(5,10);
$y = mt_rand(7,13);
imagestring($this->img,$this->font_size,$x,$y,$code,$color);
$this->captcha .= $code;
}
}
//创建点状干扰
private function create_pix(){
$color = imagecolorallocate($this->img,mt_rand(150,200),mt_rand(150,200),mt_rand(150,200));
//将点花在花板上
for ($i=0;$i<400;$i++){
imagesetpixel($this->img,mt_rand(0,$this->width),mt_rand(0,$this->height),$color);
}
}
//显示图片
public function showimg(){
header('content-type:image/png');
imagepng($this->img);
imagedestroy($this->img);
}
}
2.captcha.html 文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>验证码</title>
</head>
<body>
<form action="check.php" method="post">
<img src="show.php" id="img" style="border: 1px solid #cccccc" alt="">
<input type="text" name="code">
<input type="submit">
</form>
</body>
<script>
function $(id) {
return document.getElementById(id);
}
var img = $('img');
img.onclick = function () {
this.src = this.src+'?'+Math.random(0,999);
}
</script>
</html>
3.show.php 调用captcha类文件显示验证码
<?php
//类的自动加载
spl_autoload_register(function ($classname){
$arr = array(
'./'
);
foreach($arr as $key =>$value){
if (file_exists($value.$classname.'.class.php')){
require $value.$classname.'.class.php';
}
}
});
//实例化验证码类
$captcha = new Captcha();
$captcha->showimg();
// 将验证码保存到session上
session_start();
$_SESSION['captcha'] = strtolower($captcha->captcha);
4.check.php检测用户输入的验证码的正确性
<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2019/10/9 0009
* Time: 9:24
*/
session_start();
$code = $_POST['code'];
if (strtolower($code)==$_SESSION['captcha']){
echo"<script>alert('验证码正确');window.location.href='captcha.html'</script>";
}else{
echo"<script>alert('验证码错误');history.back()</script>";
}