Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

php验证码工具类

作者:我在坚强也需要有人疼   发布日期:2026-03-14   浏览:265

以下是一个简单的PHP验证码工具类的示例代码:

class Captcha {
    protected $width;
    protected $height;
    protected $length;
    protected $fontSize;
    protected $fontFile;
    protected $code;

    public function __construct($width = 120, $height = 40, $length = 4, $fontSize = 20, $fontFile = '') {
        $this->width = $width;
        $this->height = $height;
        $this->length = $length;
        $this->fontSize = $fontSize;
        $this->fontFile = $fontFile;
    }

    public function generate() {
        // 创建画布
        $image = imagecreatetruecolor($this->width, $this->height);

        // 设置背景色
        $backgroundColor = imagecolorallocate($image, 255, 255, 255);
        imagefill($image, 0, 0, $backgroundColor);

        // 生成随机验证码
        $this->code = $this->generateCode();

        // 绘制验证码
        $textColor = imagecolorallocate($image, 0, 0, 0);
        $x = ($this->width - $this->fontSize * $this->length) / 2;
        $y = ($this->height - $this->fontSize) / 2 + $this->fontSize;
        imagettftext($image, $this->fontSize, 0, $x, $y, $textColor, $this->fontFile, $this->code);

        // 添加干扰线
        for ($i = 0; $i < 5; $i++) {
            $lineColor = imagecolorallocate($image, rand(0, 255), rand(0, 255), rand(0, 255));
            imageline($image, rand(0, $this->width), rand(0, $this->height), rand(0, $this->width), rand(0, $this->height), $lineColor);
        }

        // 输出图像
        header('Content-type: image/png');
        imagepng($image);
        imagedestroy($image);
    }

    public function getCode() {
        return $this->code;
    }

    protected function generateCode() {
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $code = '';
        for ($i = 0; $i < $this->length; $i++) {
            $code .= $characters[rand(0, strlen($characters) - 1)];
        }
        return $code;
    }
}

// 使用示例
$captcha = new Captcha();
$captcha->generate();
$code = $captcha->getCode();
echo $code;

这个工具类可以生成一个指定长度的验证码,并在生成的图像中显示出来。可以通过调用generate()方法生成验证码图像,并通过getCode()方法获取生成的验证码。

上一篇:php的.是什么意思

下一篇:php 页面内关注公众号

大家都在看

php session用法

php 定义常量

php soapclient

phpisset函数

php html转图片

php后端

php爬虫框架

php多线程与并发

php读取csv文件

php+mysql动态网站开发

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站