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

How to implement a PHP image CAPTCHA?

How to implement a PHP image CAPTCHA?

Example of using a PHP class to generate a CAPTCHA:

class Captcha
{
    protected $width = 100; // 验证码宽度
    protected $height = 30; // 验证码高度
    protected $length = 4; // 验证码长度
    protected $font_size = 16; // 验证码字体大小

    public function generate()
    {
        session_start(); // 启动会话

        // 创建图像对象
        $image = imagecreatetruecolor($this->width, $this->height);

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

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

        // 把验证码字符串存入会话变量
        $_SESSION['captcha'] = $str;

        // 绘制验证码字符串
        $text_color = imagecolorallocate($image, 0, 0, 0);
        for ($i = 0; $i < $this->length; $i++) {
            $x = ($this->width / $this->length) * $i + ($this->width / $this->length - $this->font_size) / 2;
            $y = $this->height / 2 + $this->font_size / 2 - 2;
            imagettftext($image, $this->font_size, mt_rand(-10, 10), $x, $y, $text_color, __DIR__ . '/arial.ttf', $str[$i]);
        }

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

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

    public function validate($value)
    {
        session_start(); // 启动会话

        if (isset($_SESSION['captcha']) && strtolower($_SESSION['captcha']) === strtolower($value)) {
            unset($_SESSION['captcha']);
            return true;
        } else {
            return false;
        }
    }
}

Example usage:

Client-side code:

<!-- 在 HTML 页面中引用验证码图片 -->
<img src="captcha.php" alt="验证码">
<!-- 提交表单时发送验证码字符串 -->
<input type="text" name="captcha">

Server-side code:

<?php
// 创建验证码对象
$captcha = new Captcha();

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

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

PS: This code is for illustrative purposes only; the encapsulation can be further refined; it is not recommended to deploy this code directly in a production environment.

微信赞赏

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…
👁 143
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']=…
👁 191
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

(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
Underfloor Heating Equipment Website Template 0064

Underfloor Heating Equipment Website Template 0064 Practical Collection Yiyou template

This EyouCMS template is designed for the underfloor heating equipment industry, featuring a professional yet comfortable design style ideal for showcasing underfloor heating products, heating systems, and project cases. It enables HVAC equipment manufacturers to showcase their products online and attract both residential and commercial clients. Template Display | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Summary of Common Installation Issues for EyouCMS | EyouCMS (EyouC...
👁 50
English Language Education Training Institution Website Template 0857

English Language Education Training Institution Website Template 0857 Practical Collection Yiyou template

This EyouCMS template is ideal for English language education and training institutions, featuring an international education design style that effectively showcases English language training programs, faculty expertise, teaching outcomes, and overseas study services. It helps English language training institutions attract students 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 (...
👁 40
(Adaptive Mobile Version) Responsive Supply Chain Website – PBootCMS Template; Source Code for Import/Export Service Companies' Websites – 0477

(Adaptive Mobile Version) Responsive Supply Chain Website – PBootCMS Template; Source Code for Import/Export Service Companies' Websites – 0477 Practical Collection pbootcms Template

This set includes an adaptive mobile-friendly brown furniture decoration and building materials PbootCMS responsive website template. The design features a warm, wooden aesthetic, making it ideal for showcasing furniture products, interior design projects, or building materials trade opportunities. It helps furniture and building materials enterprises showcase their brands online and attract both renovation companies and consumers. Template Preview | Installation Instructions | Website Backend: /admin.php | Username: admin | Password: admin | Extraction Password: www.4s5.cn...
👁 46
Responsive interior design and building materials flooring website template 0065

Responsive interior design and building materials flooring website template 0065 Practical Collection Yiyou template

An eyouCMS responsive website template designed for flooring product manufacturers and construction material companies. Its fashionable, modern design effectively showcases flooring products, installation outcomes, and spatial applications. This template helps flooring brands enhance their online presence and attract both construction firms and consumers. Template Display | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Summary of Common Installation Issues for eyouCMS | eyouCMS (...
👁 61
Responsive Early Childhood Education Website Template 0858

Responsive Early Childhood Education Website Template 0858 Practical Collection Yiyou template

A eyoucms responsive website template for the infant early education enlightenment industry. The design style is lively and childlike fun, which can show the early education enlightenment course, teaching environment, teachers and educational concept. It will help early education agencies to attract parents online and enhance their brand awareness. Template display, installation instructions website background: / login.php account: admin password: admin related article easy you CMS installation FAQ summary easy you...
👁 40