PHP实现自定义验证码功能

本文介绍了一种使用PHP GD库生成验证码的方法,包括验证码图片的尺寸、文字大小、干扰点、干扰线、颜色设置等,同时提供了前后端交互的示例,实现验证码的生成、显示与验证。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

验证码在我们浏览网页的时候随处可见,尤其是在注册登录表单当中,它的存在可以有效防止防止:恶意破解密码、刷票、论坛灌水,防止某个黑客对某一个特定注册用户用特定程序暴力破解方式进行不断的登陆尝试,实际上用验证码是现在很多网站通行的方式,我们利用比较简易的方式实现了这个功能。

一、验证码类:capthca.php

在Capthca类中我们实现验证码的图片尺寸、文字大小、干扰点、干扰线、颜色、验证码源字符串等功能,主要用到的是PHP中GD库相关知识。

<?php

class Capthca
{
    //验证码图片宽度
    protected int $width;
    //验证码图片高度
    protected int $height;
    //验证码位数
    protected int $length;
    //验证码字符串
    protected string $str;
    //验证码文字大小
    protected int $size;
    //验证码字体
    protected string $font;
    //干扰线数量
    protected int $line;
    //干扰点数量
    protected int $pixel;
    //生成的验证码
    protected $code;
    //图像资源
    protected $res;

    public function __construct(int $width = 100, int $height = 30, int $length = 5, int $size = 80, int $line = 6, int $pixel = 300, string $font = 'fonts/OPPOSans.ttf', string $str = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ")
    {
        $this->width = $width;
        $this->height = $height;
        $this->length = $length;
        $this->size = $size;
        $this->line = $line;
        $this->pixel = $pixel;
        $this->font = realpath($font);
        $this->str = $str;
    }

    //渲染
    public function make()
    {
        $this->res = imagecreatetruecolor($this->width, $this->height);
        imagefill($this->res, 0, 0, imagecolorallocate($this->res, 200, 200, 200));
        $this->code();
        $this->line();
        $this->pixel();
        $this->show();
        return $this->code;
    }

    //验证码
    protected function code()
    {
        for ($i = 0; $i < $this->length; $i++) {
            $text = strtoupper($this->str[mt_rand(0, strlen($this->str) - 1)]);
            $angle = mt_rand(-20, 20);
            $box = imagettfbbox($this->size, $angle, $this->font, $this->str);
            $boxWidth = abs($box[2] - $box[0]);
            $boxHeight = abs($box[1] - $box[7]);
            $xPoint = $this->width / $this->length * $i;
            $yPoint = $this->height / 2 + $boxHeight / 2;
            imagettftext($this->res, $this->size, $angle, $xPoint, $yPoint, $this->codeColor(), $this->font, $text);
            $this->code.=$text;
        }
    }

    //渲染
    protected function show()
    {
        header("Content-type:image/png");
        imagepng($this->res);
    }

    //干扰点
    protected function pixel()
    {
        for ($i = 0; $i < $this->pixel; $i++) {
            imagesetpixel($this->res, mt_rand(0, $this->width), mt_rand(0, $this->height), $this->color());
        }
    }

    //干扰线
    protected function line()
    {
        for ($i = 0; $i < $this->line; $i++) {
            imagesetthickness($this->res, mt_rand(1, 5));
            imageline($this->res, mt_rand(0, $this->width), mt_rand(0, $this->height), mt_rand(0, $this->width), mt_rand(0, $this->height), $this->color());
        }
    }

    //生成随机颜色
    protected function color()
    {
        return imagecolorallocate($this->res, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255));
    }

    //验证码文字颜色
    protected function codeColor()
    {
        return imagecolorallocate($this->res, mt_rand(0, 150), mt_rand(0, 150), mt_rand(0, 150));
    }
}
后台调用:controller.php

如果要实现验证码功能的话,可以调用Capthca类中的make方法输出验证码,也可以在实例化的时候向构造函数传递相关参数改变验证码图片的尺寸、文字、颜色等。在这里我们将生成的验证码图片返还给前台页面,并将验证码内容通过Session保存起来!

<?php
session_start();
include "capthca.php";
$font = realpath('fonts/OPPOSans.ttf');
$capthca = new Capthca(500,150,4,80,7,400,$font,'abadklcjdttq');
$code = $capthca->make();
$_SESSION['captcha'] = $code;
前台显示:index.html

前台表单没什么好说的,具体样式可以自己定义,这里只是简单实现展示后台返回的验证码图片,并将用户输入的验证码提交到后台进行验证比对!

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
<form action="verification.php" method="post">
    <table border="1">
        <tr>
            <td>
                <input type="text" name="captcha">
            </td>
            <td>
                <img src="controller.php" alt="验证码" onclick="this.src='controller.php?'+Math.random()">
            </td>
        </tr>
    </table>
    <button class="">提交</button>
</form>
</body>
</html>
后台验证:verification.php

后台获得前台用户输入并提交的验证码后,和存储在Sessioin中的验证码内容进行比对,如果验证成功则提示“验证码正确”,如何验证不成功则提示“验证码错误”!至于验证成功或者错误后向用户展示什么内容,或者下壹步要实现什么操作,视情发挥!

<?php
header("Content-type: text/html; charset=UTF-8");
session_start();
$captcha = $_POST["captcha"];
if (strtoupper($captcha)==$_SESSION["captcha"]){
    echo "验证码正确";
}else{
    echo "验证码错误";
}

好吧,作为PHP学习过程中的壹个小Demo就先记录于此!如果有纰漏的地方,还请看到此文章的同仁不吝指出,我会及时修正相关错误!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值