Hongmu Notes
Home Language Notes How to implement a PHP image CAPTCHA? – Enhanced encapsulation
Language Notes PHP

How to implement a PHP image CAPTCHA? – Enhanced encapsulation

How to implement a PHP image CAPTCHA? – Enhanced encapsulation

Here is a more comprehensive验证码 class:

/**
 * 验证码生成工具类
 */
class Captcha
{
    protected $length = 4; // 验证码长度
    protected $fonts = ['arial.ttf']; // 验证码字体
    protected $width = 100; // 验证码宽度
    protected $height = 40; // 验证码高度
    protected $bg_color = [255, 255, 255]; // 背景颜色
    protected $text_color = [0, 0, 0]; // 验证码字体颜色
    protected $pixel_noise = 0; // 像素噪点密度
    protected $line_noise = 0; // 直线噪点密度

    public function __construct($options = [])
    {
        foreach ($options as $key => $value) {
            $this->$key = $value;
        }
    }

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

        // 设定背景色
        $bg_color = imagecolorallocate($image, ...$this->bg_color);
        imagefill($image, 0, 0, $bg_color);

        // 生成验证码字符串
        $chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
        $str = '';
        for ($i = 0; $i < $this->length; $i++) {
            $str .= $chars[mt_rand(0, strlen($chars) - 1)];
        }

        // 绘制验证码字符串
        $text_color = imagecolorallocate($image, ...$this->text_color);
        $char_width = $this->width / $this->length;
        $char_height = $this->height - 8;
        $font_size = $char_height * 0.75;
        foreach (str_split($str) as $i => $char) {
            $font_file = __DIR__ . '/fonts/' . $this->fonts[mt_rand(0, count($this->fonts) - 1)];
            $angle = mt_rand(-10, 10);
            $x = $char_width * $i + ($char_width - $font_size) / 2;
            $y = $char_height + $font_size / 2 - 4;
            imagettftext($image, $font_size, $angle, $x, $y, $text_color, $font_file, $char);
        }

        // 添加像素噪点
        if ($this->pixel_noise > 0) {
            for ($i = 0; $i < $this->pixel_noise; $i++) {
                $x = mt_rand(0, $this->width);
                $y = mt_rand(0, $this->height);
                $color = imagecolorallocate($image, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255));
                imagesetpixel($image, $x, $y, $color);
            }
        }

        // 添加直线噪点
        if ($this->line_noise > 0) {
            for ($i = 0; $i < $this->line_noise; $i++) {
                $x1 = mt_rand(0, $this->width);
                $y1 = mt_rand(0, $this->height);
                $x2 = mt_rand(0, $this->width);
                $y2 = mt_rand(0, $this->height);
                $color = imagecolorallocate($image, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255));
                imageline($image, $x1, $y1, $x2, $y2, $color);
            }
        }

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

        // 释放资源
        imagedestroy($image);

        // 把验证码字符串存储到会话中
        session_start();
        $_SESSION['captcha'] = strtolower($str);
    }

    public function validate($input)
    {
        session_start();
        $captcha = isset($_SESSION['captcha']) ? $_SESSION['captcha'] : '';
        unset($_SESSION['captcha']);
        return strtolower($input) === strtolower($captcha);
    }
}

Example usage:

// 实例化验证码生成器
$captcha = new Captcha([
    'length' => 4, // 验证码长度
    'width' => 120, // 验证码宽度
    'height' => 32, // 验证码高度
    'bg_color' => [240, 240, 240], // 背景颜色
    'text_color' => [20, 20, 20], // 字体颜色
    'pixel_noise' => 50, // 像素噪点密度
    'line_noise' => 5,  // 直线噪点密度
]);

// 生成验证码
$captcha->generate();

// 验证验证码
if ($captcha->validate($_POST['captcha'])) {
    echo '验证通过';
} else {
    echo '验证失败';
}

This验证码 class features the following improvements:

  • Parameters can be passed via the constructor, eliminating the need for manual configuration through class attributes;
  • Multiple font files can be configured; when generating a CAPTCHA, one font is selected randomly each time.
  • You can configure pixel noise and linear noise density.
微信赞赏

WeChat

支付宝赞赏

Alipay

✍️ Author: Hong Mu

webmaster · Thanks for reading, stay tuned for more exciting content

Author homepage View home page →

Related articles

PHP ob function record

PHP ob function record Language Notes PHP

Usage of the following three functions ob_get_contents(); ob_end_clean(); ob_start(); You can use these functions to buffer local files and execute local script code. Use ob_start() to save the output code into the buffer, and the page will not be displayed; then use ob_get_contents to get the data in the buffer. o…
👁 141
PHP preg

PHP preg Language Notes PHP

The preg_match_all function is used to perform a global regular expression match. preg_match_all() Syntax int preg_match_all ( string $pattern , string $subject [, array &$matches [, int $flags = PREG…
👁 169
Detailed explanation of PHP ternary operator and if

Detailed explanation of PHP ternary operator and if Language Notes PHP

Ternary operator condition ? Result 1 : Result 2 Explanation: The position in front of the question mark is the condition for judgment. If the condition is met, the result is 1, and if it is not met, the result is 2. This article compares and explains the ternary operator and if...else... in detail. I hope it will be helpful to everyone. Today when I was revising my paper online, I encountered a statement that I couldn’t understand: $if_summary = $row['IF_SUMMARY']=…
👁 189
PHP cast type

PHP cast type Language Notes PHP PHP collection PHP and mysql

Get the data type 1. If you want to check the value and type of an expression, use var_dump(). 2. If you just want to get an easy-to-read type expression for debugging, use gettype(). 3. To check a certain type, do not use gettype(), but use the is_type() function. Converting Strings to Numbers When a string is evaluated as a number, the result is determined according to the following rules...
👁 232

Recommended reading

Responsive sand-making and conveying system website template 0061

Responsive sand-making and conveying system website template 0061 Practical Collection Yiyou template

This EyouCMS responsive template is ideal for enterprises specializing in sand production and conveying systems. Its professional industrial design style is perfect for showcasing sand production equipment, conveying system products, and project case studies. It enables mining machinery companies to present their products online and attract clients from the mining and construction sectors. Template Display | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Summary of Common Installation Issues for EyouCMS | EyouCMS...
👁 42
(Adaptive mobile version) Responsive website template for tile and marble construction materials – PBootCMS template; Download HTML5 construction materials website template – 0475

(Adaptive mobile version) Responsive website template for tile and marble construction materials – PBootCMS template; Download HTML5 construction materials website template – 0475 Practical Collection pbootcms Template

This set includes an adaptive, wide-screen water purification system for mobile devices and a smart electronic device – PbootCMS website template. The modern, tech-driven design is ideal for showcasing water purification products, smart hardware, and related solutions. It helps water purification brands effectively present their products online and attract both residential and commercial customers. Template Display | Installation Instructions | Website Backend: /admin.php | Username: admin | Password: admin | Extraction Password: www.4s5.c...
👁 55
Vocational Education and Training Institution Website Template 0855

Vocational Education and Training Institution Website Template 0855 Practical Collection Yiyou template

This EyouCMS template is ideal for vocational education and training institutions, featuring a professional design style perfect for showcasing vocational courses, training programs, employment services, and faculty resources. It helps vocational training organizations attract learners online and enhance their brand awareness. Template Display | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Summary of Common Installation Issues for EyouCMS | EyouCMS (...
👁 33
Responsive interior design and building materials website template – 0063

Responsive interior design and building materials website template – 0063 Practical Collection Yiyou template

An eyouCMS responsive website template designed for home renovation and building materials enterprises. Its modern and professional design effectively showcases building materials products, renovation projects, and brand identity. This template helps building materials brands attract renovation companies and property owners online, thereby enhancing brand awareness. Template Display | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Summary of Common Installation Issues for eyouCMS | eyouCMS (...
👁 37
(Adaptive Mobile Version) PBootCMS template for humorous joke websites – Download source code for funny image-based websites – 0476

(Adaptive Mobile Version) PBootCMS template for humorous joke websites – Download source code for funny image-based websites – 0476 Practical Collection pbootcms Template

An adaptive mobile-friendly PbootCMS website template designed for mechanical manufacturing and blue-collar industrial machinery enterprises, ideal for showcasing their product ranges. It helps machinery companies build an online brand presence and attract industrial clients. Template Overview | Installation Instructions | Website Backend: /admin.php | Username: admin | Password: admin | Extraction Password: www.4s5.cn | Related Articles...
👁 56
Children's Education and Training Institution Website Template 0856

Children's Education and Training Institution Website Template 0856 Practical Collection Yiyou template

An EyouCMS website template designed specifically for children's educational and training institutions. Its vibrant and educational design enables effective presentation of children's training programs, teaching environments, faculty expertise, and student achievements. This template helps children's education institutions attract parents online and enhance their brand image. Template Display | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Summary of Common Installation Issues for EyouCMS | EyouCMS...
👁 54