search
HomeBackend DevelopmentPHP TutorialPHP implements dynamic random verification code mechanism (CAPTCHA)

php implements dynamic random verification code mechanism

CAPTCHA is the abbreviation of "Completely Automated Public Turing test to tell Computers and Humans Apart". It is a public fully automated program that distinguishes whether the user is a computer or a human. It can prevent: malicious cracking of passwords, ticket fraud, forum flooding, and effectively prevents a hacker from using a specific program to violently crack a specific registered user from making continuous login attempts. In fact, using verification codes is a common method for many websites now. We use This function is implemented in a relatively simple way.

This question can be generated and judged by a computer, but only a human can answer it. Since computers cannot answer CAPTCHA questions, the user who answers the questions can be considered a human.

PHP production dynamic verification code is based on PHP image processing. Let's first introduce the image processing of PHP.

Introduction to .php image processing

In PHP5, processing dynamic images is much easier than before. PHP5 includes the GD extension package in the php.ini file. You only need to remove the corresponding comments of the GD extension package to use it normally. The GD library included in PHP5 is the upgraded GD2 library, which contains some useful JPG functions that support true color image processing.

  Generally generated graphics are stored in PHP's document format, but dynamic graphics can be directly obtained through HTML's image insertion method SRC. For example, verification code, watermark, thumbnail, etc.

General process for creating images:

1). Set the header to tell the browser the MIME type you want to generate.

2). Create an image area, and all subsequent operations will be based on this image area.

3).Draw a filled background in the blank image area.

4). Draw graphic outlines on the background to enter text.

5).Output the final graphics.

6). Clear all resources.

7). Call images from other pages.

The first step is to set the file MIME type and output type. Change the output type to image stream
header('Content-Type: image/png;');

Generally generated images can be png, jpeg, gif, wbmp

The second step is to create a graphics area and image background

imagecreatetruecolor() returns an image identifier representing a black image of size x_size and y_size. Syntax: resource imagecreatetruecolor ( int $width , int $height )

$im = imagecreatetruecolor(200,200);

The third step is to draw a filled background in the blank image area

Requires a color filler; imagecolorallocate -- assigns a color to an image; Syntax: int imagecolorallocate ( resource $image , int $red , int $green , int $blue )

$blue = imagecolorallocate($im,0,102,255);

Fill this blue color into the background; imagefill -- area filling; Syntax: bool imagefill ( resource $image , int $x , int $y , int $color )

imagefill($im,0,0,$blue);

The fourth step is to enter some lines, text, etc. on the blue background

Color Filler

$white = imagecolorallocate($im,255,255,255);

Draw two line segments: imageline

imageline() draws a line segment in the image image using the color color from coordinates x1, y1 to x2, y2 (the upper left corner of the image is 0, 0). Syntax: bool imageline ( resource $image , int $x1 , int $y1 , int $x2 , int $y2 , int $color )

imageline($im,0,0,200,200,$white);

imageline($im,200,0,0,200,$white);

Draw a line of string horizontally: imagestring

imagestring() uses col color to draw the string s to the x, y coordinates of the image represented by image (this is the coordinate of the upper left corner of the string, the upper left corner of the entire image is 0,0). If font is 1, 2, 3, 4 or 5, the built-in font is used. Syntax: bool imagestring ( resource $image , int $font , int $x , int $y , string $s , int $col )

imagestring($im,5,66,20,'jingwhale',$white);

Step 5, output the final graphics

imagepng() Outputs a GD image stream (image) in PNG format to standard output (usually a browser), or to a file if a filename is given with filename. Syntax: bool imagepng ( resource $image [, string $filename ] )

imagepng($im);

Step six, I want to clear all resources

imagedestroy() frees the memory associated with image. Syntax: bool imagedestroy ( resource $image )

imagedestroy($im);

Call the graphics created by other pages (html)

The sample code is as follows:

<span>php
    </span><span>//</span><span>第一步,设置文件MIME类型</span>
    <span>header</span>('Content-Type: image/png;'<span>);
    
    </span><span>//</span><span>第二步,创建一个图形区域,图像背景</span>
    <span>$im</span> = imagecreatetruecolor(200,200<span>);
    
    </span><span>//</span><span>第三步,在空白图像区域绘制填充背景</span>
    <span>$blue</span> = imagecolorallocate(<span>$im</span>,0,102,255<span>);    
    imagefill(</span><span>$im</span>,0,0,<span>$blue</span><span>);
    
    </span><span>//</span><span>第四步,在蓝色的背景上输入一些线条,文字等</span>
    <span>$white</span> = imagecolorallocate(<span>$im</span>,255,255,255<span>);
    imageline(</span><span>$im</span>,0,0,200,200,<span>$white</span><span>);
    imageline(</span><span>$im</span>,200,0,0,200,<span>$white</span><span>);
    imagestring(</span><span>$im</span>,5,66,20,'Jing.Whale',<span>$white</span><span>);
    
    </span><span>//</span><span>第五步,输出最终图形</span>
    imagepng(<span>$im</span><span>);
    
    </span><span>//</span><span>第六步,我要将所有的资源全部清空</span>
    imagedestroy(<span>$im</span><span>);    
</span>?>

Display effect:

2. Create dynamic verification code

Attached: Code source addresshttps://github.com/cnblogs-/php-captcha

1. Create a picture with verification code and blur the background

The random code uses hexadecimal; the blurred background means adding lines, snowflakes, etc. to the background of the picture.

1) Create random code

<span>for</span> (<span>$i</span>=0;<span>$i</span>$_rnd_code;<span>$i</span>++<span>) {
        </span><span>$_nmsg</span> .= <span>dechex</span>(<span>mt_rand</span>(0,15<span>));
    }</span>

string dechex (int $number), returns a string containing the hexadecimal representation of the given number parameter.

2) Save in session

<span>$_SESSION</span>['code'] = <span>$_nms</span>

3)Create pictures

<span>//</span><span>创建一张图像</span>
<span>$_img</span> = imagecreatetruecolor(<span>$_width</span>,<span>$_height</span><span>);

</span><span>//</span><span>白色</span>
<span>$_white</span> = imagecolorallocate(<span>$_img</span>,255,255,255<span>);

</span><span>//</span><span>填充</span>
imagefill(<span>$_img</span>,0,0,<span>$_white</span><span>);

</span><span>if</span> (<span>$_flag</span><span>) {
</span><span>//</span><span>黑色,边框</span>
    <span>$_black</span> = imagecolorallocate(<span>$_img</span>,0,0,0<span>);
    imagerectangle(</span><span>$_img</span>,0,0,<span>$_width</span>-1,<span>$_height</span>-1,<span>$_black</span><span>);
}</span>

4) Blur background

<span>//</span><span>随即画出6个线条</span>
<span>for</span> (<span>$i</span>=0;<span>$i</span>$i++<span>) {
</span><span>   $_rnd_color</span> = imagecolorallocate(<span>$_img</span>,<span>mt_rand</span>(0,255),<span>mt_rand</span>(0,255),<span>mt_rand</span>(0,255<span>));
   imageline(</span><span>$_img</span>,<span>mt_rand</span>(0,<span>$_width</span>),<span>mt_rand</span>(0,<span>$_height</span>),<span>mt_rand</span>(0,<span>$_width</span>),<span>mt_rand</span>(0,<span>$_height</span>),<span>$_rnd_color</span><span>);
   }

</span><span>//随机</span><span>雪花</span>
<span>for</span> (<span>$i</span>=0;<span>$i</span>$i++<span>) {
   </span><span>$_rnd_color</span> = imagecolorallocate(<span>$_img</span>,<span>mt_rand</span>(200,255),<span>mt_rand</span>(200,255),<span>mt_rand</span>(200,255<span>));
   imagestring(</span><span>$_img</span>,1,<span>mt_rand</span>(1,<span>$_width</span>),<span>mt_rand</span>(1,<span>$_height</span>),'*',<span>$_rnd_color</span><span>);
   }</span>

5) Output and destruction

<span>//</span><span>输出验证码</span>
<span>for</span> (<span>$i</span>=0;<span>$i</span>strlen(<span>$_SESSION</span>['code']);<span>$i</span>++<span>) {
        </span><span>$_rnd_color</span> = imagecolorallocate(<span>$_img</span>,<span>mt_rand</span>(0,100),<span>mt_rand</span>(0,150),<span>mt_rand</span>(0,200<span>));
        imagestring(</span><span>$_img</span>,5,<span>$i</span>*<span>$_width</span>/<span>$_rnd_code</span>+<span>mt_rand</span>(1,10),<span>mt_rand</span>(1,<span>$_height</span>/2),<span>$_SESSION</span>['code'][<span>$i</span>],<span>$_rnd_color</span><span>);
    }

</span><span>//</span><span>输出图像</span>
<span>header</span>('Content-Type: image/png'<span>);
imagepng(</span><span>$_img</span><span>);

</span><span>//</span><span>销毁</span>
imagedestroy(<span>$_img</span>);

Encapsulate it in the global.func.php global function library, and the function name is _code() for easy calling. We will set the four parameters $_width, $_height, $_rnd_code, $_flag to enhance the flexibility of the function.

* @param int $_width The length of the verification code: if you want 6 digits, 75+50 is recommended; if you want 8 digits, 75+50+50 is recommended, and so on
* @param int $_height The height of the verification code
* @ param int $_rnd_code The number of digits in the verification code
* @param bool $_flag Whether the verification code requires a border: true with border, false without border (default)

The encapsulated code is as follows:

<span>php 
</span><span>/*</span><span>*
 *      [verification-code] (C)2015-2100 jingwhale.
 *      
 *      This is a freeware
 *      $Id: global.func.php 2015-02-05 20:53:56 jingwhale$
 </span><span>*/</span>
<span>/*</span><span>*
 * _code()是验证码函数
 * @access public
 * @param int $_width 验证码的长度:如果要6位长度推荐75+50;如果要8位,推荐75+50+50,依次类推
 * @param int $_height 验证码的高度
 * @param int $_rnd_code 验证码的位数
 * @param bool $_flag 验证码是否需要边框:true有边框, false无边框(默认)
 * @return void 这个函数执行后产生一个验证码
 </span><span>*/</span>
<span>function</span> _code(<span>$_width</span> = 75,<span>$_height</span> = 25,<span>$_rnd_code</span> = 4,<span>$_flag</span> = <span>false</span><span>) {

    </span><span>//</span><span>创建随机码</span>
    <span>for</span> (<span>$i</span>=0;<span>$i</span>$_rnd_code;<span>$i</span>++<span>) {
        </span><span>$_nmsg</span> .= <span>dechex</span>(<span>mt_rand</span>(0,15<span>));
    }

    </span><span>//</span><span>保存在session</span>
    <span>$_SESSION</span>['code'] = <span>$_nmsg</span><span>;

    </span><span>//</span><span>创建一张图像</span>
    <span>$_img</span> = imagecreatetruecolor(<span>$_width</span>,<span>$_height</span><span>);

    </span><span>//</span><span>白色</span>
    <span>$_white</span> = imagecolorallocate(<span>$_img</span>,255,255,255<span>);

    </span><span>//</span><span>填充</span>
    imagefill(<span>$_img</span>,0,0,<span>$_white</span><span>);

    </span><span>if</span> (<span>$_flag</span><span>) {
        </span><span>//</span><span>黑色,边框</span>
        <span>$_black</span> = imagecolorallocate(<span>$_img</span>,0,0,0<span>);
        imagerectangle(</span><span>$_img</span>,0,0,<span>$_width</span>-1,<span>$_height</span>-1,<span>$_black</span><span>);
    }

    </span><span>//</span><span>随即画出6个线条</span>
    <span>for</span> (<span>$i</span>=0;<span>$i</span>$i++<span>) {
        </span><span>$_rnd_color</span> = imagecolorallocate(<span>$_img</span>,<span>mt_rand</span>(0,255),<span>mt_rand</span>(0,255),<span>mt_rand</span>(0,255<span>));
        imageline(</span><span>$_img</span>,<span>mt_rand</span>(0,<span>$_width</span>),<span>mt_rand</span>(0,<span>$_height</span>),<span>mt_rand</span>(0,<span>$_width</span>),<span>mt_rand</span>(0,<span>$_height</span>),<span>$_rnd_color</span><span>);
    }

    </span><span>//</span><span>随即雪花</span>
    <span>for</span> (<span>$i</span>=0;<span>$i</span>$i++<span>) {
        </span><span>$_rnd_color</span> = imagecolorallocate(<span>$_img</span>,<span>mt_rand</span>(200,255),<span>mt_rand</span>(200,255),<span>mt_rand</span>(200,255<span>));
        imagestring(</span><span>$_img</span>,1,<span>mt_rand</span>(1,<span>$_width</span>),<span>mt_rand</span>(1,<span>$_height</span>),'*',<span>$_rnd_color</span><span>);
    }

    </span><span>//</span><span>输出验证码</span>
    <span>for</span> (<span>$i</span>=0;<span>$i</span>strlen(<span>$_SESSION</span>['code']);<span>$i</span>++<span>) {
        </span><span>$_rnd_color</span> = imagecolorallocate(<span>$_img</span>,<span>mt_rand</span>(0,100),<span>mt_rand</span>(0,150),<span>mt_rand</span>(0,200<span>));
        imagestring(</span><span>$_img</span>,5,<span>$i</span>*<span>$_width</span>/<span>$_rnd_code</span>+<span>mt_rand</span>(1,10),<span>mt_rand</span>(1,<span>$_height</span>/2),<span>$_SESSION</span>['code'][<span>$i</span>],<span>$_rnd_color</span><span>);
    }

    </span><span>//</span><span>输出图像</span>
    <span>header</span>('Content-Type: image/png'<span>);
    imagepng(</span><span>$_img</span><span>);

    </span><span>//</span><span>销毁</span>
    imagedestroy(<span>$_img</span><span>);
}
</span>?>
2. Create a verification mechanism

Create a PHP verification page and check whether the verification code is consistent through session.

1) Create verification-code.php verification page

<span>php 
</span><span>/*</span><span>*
 *      [verification-code] (C)2015-2100 jingwhale.
 *
 *      This is a freeware
 *      $Id: verification-code.php 2015-02-05 20:53:56 jingwhale$
 </span><span>*/</span>

<span>//</span><span>设置字符集编码</span>
<span>header</span>('Content-Type: text/html; charset=utf-8'<span>);
</span>?>




    <meta charset="UTF-8">
    <title>verification code</title>
    <link rel="stylesheet" type="text/css" href="style/basic.css">



    <div>
        <form method="post" name="verification" action="verification-code.php?action=verification">
            dl>
                <dd>验证码:<input type="text" name="code">class="code" /><img  src="/static/imghwm/default1.png" data-src="codeimg.php" class="lazy" alt="PHP implements dynamic random verification code mechanism (CAPTCHA)" >
</dd>
                <dd>
<input type="submit">class="submit" value="验证" /></dd>
            <span>dl</span>>
        </form>
    </div>


Displayed as follows:

2) Create a page to generate verification code

Create codeimg.php to provide verification code images for img in verification-code.php html code

First you must open the session on the codeimg.php page;

Secondly, introduce our encapsulated global.func.php global function library;

Finally, run_code();

<span>php 
</span><span>/*</span><span>*
 *      [verification-code] (C)2015-2100 jingwhale.
 *      
 *      This is a freeware
 *      $Id: codeimg.php 2015-02-05 20:53:56 jingwhale$
 </span><span>*/</span>

<span>//</span><span>开启session</span>
<span>session_start</span><span>();

</span><span>//</span><span>引入全局函数库(自定义)</span>
<span>require</span> <span>dirname</span>(<span>__FILE__</span>).'/includes/global.func.php'<span>;

</span><span>//</span><span>运行验证码函数。通过数据库的_code方法,设置验证码的各种属性,生成图片</span>
_code(125,25,6,<span>false</span><span>);

</span>?>

3) Create session verification mechanism

First, you must open the session on the verification-code.php page;

Secondly, design the way to submit the verification code. This article is submitted in the get method. When action=verification, the submission is successful;

Finally, create a verification function. The principle is to check whether the verification code submitted by the client user is consistent with the verification code of the session in the server codeimg.php; there is a js pop-up function _alert_back(), and we also encapsulate it in global. in func.php;

Modify the php code in verification-code.php as follows:

<span>php 
</span><span>/*</span><span>*
 *      [verification-code] (C)2015-2100 jingwhale.
 *
 *      This is a freeware
 *      $Id: verification-code.php 2015-02-05 20:53:56 jingwhale$
 </span><span>*/</span>

<span>//</span><span>设置字符集编码</span>
<span>header</span>('Content-Type: text/html; charset=utf-8'<span>);

</span><span>//</span><span>开启session</span>
<span>session_start</span><span>();

</span><span>//</span><span>引入全局函数库(自定义)</span>
<span>require</span> <span>dirname</span>(<span>__FILE__</span>).'/includes/global.func.php'<span>;

</span><span>//</span><span>检验验证码</span>
<span>if</span> (<span>$_GET</span>['action'] == 'verification'<span>) {
    
    </span><span>if</span> (!(<span>$_POST</span>['code'] == <span>$_SESSION</span>['code'<span>])) {
        _alert_back(</span>'验证码不正确!'<span>);
    }</span><span>else</span><span>{
        _alert_back(</span>'验证码通过!'<span>);
    }
}  
</span>?>




    <meta charset="UTF-8">
    <title>verification code</title>
    <link rel="stylesheet" type="text/css" href="style/basic.css">
    <script type="text/javascript" src="js/codeimg.js"></script>



    <div>
        <form method="post" name="verification" action="verification-code.php?action=verification">
            dl>
                <dd>验证码:<input type="text" name="code">class="code" /><img  src="/static/imghwm/default1.png" data-src="codeimg.php" class="lazy" alt="PHP implements dynamic random verification code mechanism (CAPTCHA)" >
</dd>
                <dd>
<input type="submit">class="submit" value="验证" /></dd>
            <span>dl</span>>
        </form>
    </div>


3. Click on the verification code image to update the verification code

If you want to update the verification code above, you must refresh the page; we write a codeimg.js function to update the verification code by clicking on the verification code image

window.onload = <span>function</span><span> () {
    </span><span>var</span> code = document.getElementById('codeimg');<span>//</span><span>通过id找到html中img标签</span>
    code.onclick = <span>function</span> () {<span>//</span><span>为标签添加点击事件</span>
        <span>this</span>.src='codeimg.php?tm='+Math.random();<span>//</span><span>修改时间,重新指向codeimg.php</span>
<span>    };    
}</span>

Then it in the verification-code.php html code head.

End

Reprinting is welcome. When reprinting, please indicate the word reprint, the original author and the original blog post address.

The above introduces the implementation of dynamic random verification code mechanism (CAPTCHA) in PHP, including various aspects. I hope it will be helpful to friends who are interested in PHP tutorials.

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment