Home > Backend Development > PHP Tutorial > About the method of making dynamic random verification code in php

About the method of making dynamic random verification code in php

不言
Release: 2023-04-01 15:08:02
Original
1839 people have browsed it

This article mainly introduces relevant information on the method of making dynamic random verification codes in PHP. Friends who need it can refer to

Verification code (CAPTCHA) is "Completely Automated Public Turing test to tell Computers and Humans "Apart" (the abbreviation of "Automated Turing Test to Distinguish Computers and Humans") is a public, fully automated program that distinguishes whether a 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’s dynamic verification code production is based on php’s image processing. Let’s first introduce php’s image processing.

1. Introduction to php image processing

In PHP5, the processing of 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 obtained directly through HTML’s image insertion method SRC. For example, verification code, watermark, thumbnail, etc.

The general process of creating an image:

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

2). Create an image area, and 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). Other pages call images.

The first step is to set the file MIME type and the output type. Change the output type to image stream

header('Content-Type: image/png;');
Copy after login

Generally the 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, which represents a black image with sizes x_size and y_size. Syntax: resource imagecreatetruecolor (int $width, int $height)

$im = imagecreatetruecolor(200,200);
Copy after login

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

There must be a color filler; imagecolorallocate -- for an image Assign color; syntax: int imagecolorallocate (resource $image, int $red, int $green, int $blue)

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

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);
Copy after login

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

Color filler

$white = imagecolorallocate($im,255,255,255);
Copy after login

Draw two line segments: imageline

imageline() Use color color to draw a line segment in the image image 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);
Copy after login

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, and 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);
Copy after login

The fifth step, output the final graphic

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

imagepng($im);
Copy after login

The sixth step is to clear all resources

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

imagedestroy($im);
Copy after login

Call the graphics created by other pages (html)

<img src="Demo4.php" alt="PHP创建的图片" />
Copy after login

The sample code is as follows:

Copy after login

Display effect:

2. Create dynamic verification code

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 a random code

for ($i=0;$i<$_rnd_code;$i++) {
        $_nmsg .= dechex(mt_rand(0,15));
    }
Copy after login

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

2) Save in session

$_SESSION[&#39;code&#39;] = $_nms
Copy after login

3) Create picture

//创建一张图像
$_img = imagecreatetruecolor($_width,$_height);
//白色
$_white = imagecolorallocate($_img,255,255,255);
//填充
imagefill($_img,0,0,$_white);
if ($_flag) {
//黑色,边框
    $_black = imagecolorallocate($_img,0,0,0);
    imagerectangle($_img,0,0,$_width-1,$_height-1,$_black);
}
Copy after login

4) Blur the background

//随机画出6个线条
for ($i=0;$i<6;$i++) {
   $_rnd_color = imagecolorallocate($_img,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255));
   imageline($_img,mt_rand(0,$_width),mt_rand(0,$_height),mt_rand(0,$_width),mt_rand(0,$_height),$_rnd_color);
   }
//随机雪花
for ($i=0;$i<100;$i++) {
   $_rnd_color = imagecolorallocate($_img,mt_rand(200,255),mt_rand(200,255),mt_rand(200,255));
   imagestring($_img,1,mt_rand(1,$_width),mt_rand(1,$_height),&#39;*&#39;,$_rnd_color);
   }
Copy after login

5)Output and destroy

//输出验证码
for ($i=0;$i<strlen($_SESSION[&#39;code&#39;]);$i++) {
        $_rnd_color = imagecolorallocate($_img,mt_rand(0,100),mt_rand(0,150),mt_rand(0,200));
        imagestring($_img,5,$i*$_width/$_rnd_code+mt_rand(1,10),mt_rand(1,$_height/2),$_SESSION[&#39;code&#39;][$i],$_rnd_color);
    }
//输出图像
header(&#39;Content-Type: image/png&#39;);
imagepng($_img);
//销毁
imagedestroy($_img);
Copy after login

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 验证码的长度:如果要6位长度推荐75+50;如果要8位,推荐75+50+50,依次类推
* @param int $_height 验证码的高度
* @param int $_rnd_code 验证码的位数
* @param bool $_flag 验证码是否需要边框:true有边框, false无边框(默认)

封装后的代码如下:

Copy after login

2.创建验证机制

创建php验证页面,通过session来检验验证码是否一致。

1)创建verification-code.php验证页面

<?php 
/**
 *      [verification-code] (C)2015-2100 jingwhale.
 *
 *      This is a freeware
 *      $Id: verification-code.php 2015-02-05 20:53:56 jingwhale$
 */
//设置字符集编码
header(&#39;Content-Type: text/html; charset=utf-8&#39;);
?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>verification code</title>
    <link rel="stylesheet" type="text/css" href="style/basic.css" />
</head>
<body>
    <p id="testcode">
        <form method="post" name="verification" action="verification-code.php?action=verification">
            <dl>
                <dd>验证码:<input type="text" name="code" class="code" /><img src="codeimg.php" id="codeimg"  /></dd>
                <dd><input type="submit" class="submit" value="验证" /></dd>
            </dl>
        </form>
    </p>
</body>
</html>
Copy after login

显示如下:

2)创建产生验证码图片页面

创建codeimg.php为verification-code.php html代码里的img提供验证码图片

首先必须在codeimg.php页面开启session;

其次,将我们封装好的global.func.php全局函数库引入进来;

最后,运行_code();

<?php 
/**
 *      [verification-code] (C)2015-2100 jingwhale.
 *      
 *      This is a freeware
 *      $Id: codeimg.php 2015-02-05 20:53:56 jingwhale$
 */
//开启session
session_start();
//引入全局函数库(自定义)
require dirname(__FILE__).&#39;/includes/global.func.php&#39;;
//运行验证码函数。通过数据库的_code方法,设置验证码的各种属性,生成图片
_code(125,25,6,false);
?>
Copy after login

3)创建session检验机制

首先必须在verification-code.php页面也开启session;

其次,设计提交验证码的方式,本文以get方式提交,当action=verification时提交成功;

最后,创建验证函数,原理是将客户端用户提交的验证码同服务器codeimg.php中session的验证码是否一致;这里有一个js弹窗函数_alert_back(),我们也把它封装在global.func.php里;

修改verification-code.php中php代码如下:

<?php 
/**
 *      [verification-code] (C)2015-2100 jingwhale.
 *
 *      This is a freeware
 *      $Id: verification-code.php 2015-02-05 20:53:56 jingwhale$
 */
//设置字符集编码
header(&#39;Content-Type: text/html; charset=utf-8&#39;);
//开启session
session_start();
//引入全局函数库(自定义)
require dirname(__FILE__).&#39;/includes/global.func.php&#39;;
//检验验证码
if ($_GET[&#39;action&#39;] == &#39;verification&#39;) {
    if (!($_POST[&#39;code&#39;] == $_SESSION[&#39;code&#39;])) {
        _alert_back(&#39;验证码不正确!&#39;);
    }else{
        _alert_back(&#39;验证码通过!&#39;);
    }
}  
?>
<!DOCTYPE html>
<html>
<head>
    <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>
</head>
<body>
    <p id="testcode">
        <form method="post" name="verification" action="verification-code.php?action=verification">
            <dl>
                <dd>验证码:<input type="text" name="code" class="code" /><img src="codeimg.php" id="codeimg"  /></dd>
                <dd><input type="submit" class="submit" value="验证" /></dd>
            </dl>
        </form>
    </p>
</body>
</html>
Copy after login

3.实现点击验证码图片更新验证码

上面若想实现验证码更新,必须刷新页面;我们写一个codeimg.js函数实现点击验证码图片更新验证码

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

然后在verification-code.php html代码head里它即可。

以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!

相关推荐:

关于PHP中Closure类的使用方法

使用PHP如何编写简单的App接口

关于php购物网站支付paypal的使用方法

The above is the detailed content of About the method of making dynamic random verification code in php. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template