本文介绍的是基于PHP实现用户注册登录功能,本项目分为四部分内容:1前端页面制作,2验证码制作,3实现注册登陆,4功能完善。具体情况可以往下看。
验证码制作
一、实验简介
本次实验将会带领大家使用面向对象的思想封装一个验证码类。并在注册和登陆界面展示使用。通过本次实验的学习,你将会领悟到 PHP 的 OOP 思想,以及 GD 库的使用,验证码生成。
1.1 涉及到的知识点
- PHP
- GD库
- OOP编程
1.2 开发工具
sublime,一个方便快速的文本编辑器。点击桌面左下角: 应用程序菜单/开发/sublime
二、封装验证码类
2.1 建立目录以及准备字体
在 web 目录下建立一个 admin 目录作为我们的后台目录,存放后台代码文件。在 admin 下建立一个 fonts 目录,用于存放制作验证码所需字体。
在 admin 下新建一个 Captcha.PHP 文件,这就是我们需要编辑的验证码类文件。
当前目录层次结构:
字体文件可通过以下命令下载到 fonts 目录:
接下来开始编写具体的方法:
创建图像资源句柄
用到的相关函数
创建验证码字符串并输出到图像
//计算每个字符间距
$diff = $this->width/$this->codeNum;
for ($i=0; $i < $this->codeNum; $i++) {
//为每个字符生成颜色(使用深色)
$txtColor = imagecolorallocate($this->img,mt_rand(100,255),255));
//写入图像
imagettftext($this->img,$this->fontSize,mt_rand(-30,30),$diff*$i+mt_rand(3,8),mt_rand(20,$this->height-10),$txtColor,$this->font,$this->code[$i]);
}
}
用到的相关函数
创建验证码字符串并输出到图像
用到的相关函数:
- imagettftext:用 TrueType 字体向图像写入文本
创建干扰线条
用到的相关函数:
- imageline:画一条线段
创建干扰点
使用的相关函数:
对外输出图像:
用到的相关函数:
对外提供验证码:
public function createImage(){
$this->img = imagecreate($this->width,$this->height);
imagecolorallocate($this->img,100));
}
public function createCode(){
$strlen = strlen($this->string)-1;
for ($i=0; $i < $this->codeNum; $i++) {
$this->code .= $this->string[mt_rand(0,$strlen)];
}
$_SESSION['code'] = $this->code;
$diff = $this->width/$this->codeNum;
for ($i=0; $i < $this->codeNum; $i++) {
$txtColor = imagecolorallocate($this->img,255));
imagettftext($this->img,$this->code[$i]);
}
}
public function createLines(){
for ($i=0; $i < 4; $i++) {
$color = imagecolorallocate($this->img,155));
imageline($this->img,$color);
}
}
public function createPiexs(){
for ($i=0; $i < 100; $i++) {
$color = imagecolorallocate($this->img,$color);
}
}
public function show()
{
$this->createImage();
$this->createCode();
if ($this->lineFlag) {
$this->createLines();
}
if ($this->piexFlag) {
$this->createPiexs();
}
header('Content-type:image/png');
imagepng($this->img);
imagedestroy($this->img);
}
public function getCode(){
return $this->code;
}
}
以上就是验证码类的全部代码。看起来确实挺简单的,不过用的图像处理函数比较多,上面相关的函数我也做了必要的链接和用途说明。这些函数也不用死记硬背,遇到不清楚的,随时查阅 PHP 官方文档,最重要的是还有中文文档。
2.2 使用验证码
既然已经封装完毕,那就可以开始使用了。这里为了方便,直接在 Captcha 类的下方调用该类:
三、前端展示