前言
最近学习了PHP的GD扩展库,就看着教程学了,如何生成验证码和验证,就把我学习的代码分享出来吧,方法大家学习,也方便我日后使用。
创建验证码类
验证码类的功能分别是生成验证码、绘制干扰点、绘制干扰线、绘制验证码、显示验证码和销毁画布资源。
创建一个Verify.php
的类文件,代码如下:
<?php
header('Content-Type:image/png');
class Verify
{
//定义验证码属性
private $code;
//定义画布资源
private $img;
//定义画笔
private $white;
private $fontcolor;
//干扰点的画笔颜色
private $pointcolor;
function __construct()
{
$this->code();
$this->init();
$this->draw();
$this->interfere();
$this->show();
}
//生成验证码
function code()
{
for($i = 0; $i < 4; $i++) {
//随机产生1,2,3其中的一个数字
$tmp = rand(1, 3);
switch ($tmp) {
case 1:
$this->code .= sprintf('%c', rand(48, 57));
break;
case 2:
$this->code .= sprintf('%c', rand(97, 122));
break;
case 3:
$this->code .= sprintf('%c', rand(65, 90));
break;
}
}
}
//保存验证码
function setcode()
{
//将验证码转为小写
$this->code = strtolower($this->code);
session_start();
$_SESSION['code']=$this->code;
}
//初始化方法
function init()
{
//创建画布
$this->img=imagecreatetruecolor(130,50);
//设置画笔
$this->white = imagecolorallocate($this->img, 255, 255, 255);
//设置画布背景颜色
imagefill($this->img,0,0,$this->white);
}
//设置干扰点
function interfere()
{
//设置干扰点
for($i=0;$i<200;$i++){
$this->pointcolor = imagecolorallocate($this->img, rand(50,200), rand(50,200), rand(50,200));
imagesetpixel($this->img,rand(1,130),rand(1,50),$this->pointcolor);
}
//设置干扰线
for($i=0;$i<5;$i++){
$this->pointcolor = imagecolorallocate($this->img, rand(80,220), rand(80,220), rand(80,220));
imageline($this->img,rand(1,129),rand(1,49),rand(1,129),rand(1,49),$this->pointcolor);
}
}
//绘制验证码
function draw()
{
for($i = 0; $i < 4; $i++){
$this->fontcolor = imagecolorallocate($this->img, rand(0,100), rand(0,100), rand(0,100));
$x = $i * 30 + 10;
imagettftext(
$this->img,
rand(20,35), //随机产生字体大小,像素级
rand(-30, 30), //随机产生字体倾斜角度
$x, //绘制起始的x坐标点
40, //绘制起始的y坐标点
$this->fontcolor,
'SIMHEI.TTF', //使用的字体
$this->code[$i]
);
}
$this->setcode();
}
function show(){
//显示验证码
imagepng($this->img);
//销毁画布
imagedestroy($this->img);
}
}
引入类
加载Verify类和显示验证码,创建code.php
文件,代码如下:
<?php
require_once 'Verify.php';
$v = new Verify();
创建登陆HTML页面
创建一个 logo.html
页面,代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>验证码验证</title>
</head>
<body>
<br>
<form action="data.php" method="get">
验证码:
<input type="text" placeholder="请输入验证码" name="code">
<img src="code.php" onclick="change(this)">
<br>
<button type="submit">提交</button>
</form>
<script type="text/javascript">
function change(obj){
obj.src = 'code.php?a=' + Math.random();
}
</script>
</body>
</html>
创建验证文件
创建data.php
文件,用户验证用户输入的验证码是否和服务器上一样,代码如下:
<?php
session_start();
//接收用户输入验证码,转为小写
$user_code = strtolower($_GET['code']);
if($user_code==$_SESSION['code']){
echo '验证码验证正确';
}else{
echo '验证码验证失败';
}
教程到这里就结束了,看下效果图吧!