Home >Backend Development >PHP Problem >How to implement image verification code in php

How to implement image verification code in php

藏色散人
藏色散人Original
2021-09-26 11:34:324612browse

How to implement image verification code in php: 1. Load the GD extension; 2. Create a canvas and add content to the canvas; 3. Save the output through imagepng; 4. Release resources; 5. Generate random verification code data That’s it.

How to implement image verification code in php

The operating environment of this article: Windows 7 system, PHP version 7.1, DELL G3 computer.

How to implement image verification code in php?

PHP realizes the picture verification code function

Verification code: captcha, is a technology used to distinguish people from computers
Principle (Completely Automated Public Turing Test to Tell Computers and Humans Apart (Full-automatic Turing Test to distinguish computers and humans)

How to distinguish computers and humans?
As long as it is textual content, computers can definitely recognize it; computers are The content of the picture cannot be recognized, but the human eye can easily identify the content of the picture.

The essence of the verification code: printing textual content on the picture to realize the difference between computers and humans.

1. Understanding image extensions

PHP itself cannot operate images.
PHP can use the provided image extensions to operate images.

There are many image extensions: the commonly used one is GD

Load GD extension: All GD extension functions begin with image

2. PHP operation pictures

1. Add canvas (create canvas)

Image resource imagecreatetruecolor(width, height);

2. Add content (text) to the canvas

a) to what will be Assign color to the content added to the picture: first associate the color with the picture resource, and then use
color handle [integer] imagecolorallocate(picture resource, red, green, blue); //Colors can use numbers 0- 255 or use hexadecimal#Hex

b) to write text: You can only write English (content on the ASCII code table)
Boolean imagestring(image resource, text size, starting X Coordinates, starting Y coordinate, writing content, color);
Font size: 1-5

3. Save the output

imagepng(image resource[,save location]);

4. Release resources (recommended release of resources)

Boolean result imagedestroy (picture resource);

//1.    创建画布
$img = imagecreatetruecolor(200,200);
//var_dump($img);

//2.    作画
//2.1   给画布分配颜色
$color = imagecolorallocate($img,255,255,255);
//echo $color;

//2.2   写入文字
$true = imagestring($img,5,50,90,'hello world',$color);
//var_dump($true);

//3.    保存输出内容
//3.1   输出
//告诉浏览器,内容是图片
//header('Content-type:image/png');
//imagepng($img);

//3.2   保存图片
imagepng($img,'hello.png'); // 保存到当前目录

//4.    释放资源
$res = imagedestroy($img);
var_dump($res);

3. Verification code picture

1. Generate random Verification code data

2. Create canvas

3. Fill background color: imagefill(image resource, starting position X, starting position Y, color handle); //imagefill: Find one After the pixel is selected, if it is found that the surrounding adjacent pixels have the same color as the current pixel (all black), they will be automatically rendered.

4. Add text content: First assign the color

5 .Save the output: Verification codes are all output

6. Release resources

//制作验证码图片

//获取验证码字符串
$captcha = '';
for($i = 0;$i < 4;$i++){
    //chr: 将数字转换成对应的字符(ASCII)
    switch(mt_rand(0,2)){
        case 0: //数字
            $captcha .= chr(mt_rand(49,57));
            break;
        case 1:    //大写字母
            $captcha .= chr(mt_rand(65,90));
            break;
        case 2: //小写字母
            $captcha .= chr(mt_rand(97,122));
            break;
    }
}
//echo $captcha;

//创建画布
$img = imagecreatetruecolor(200,200);

//给背景分配颜色
$bg = imagecolorallocate($img,mt_rand(200,255),mt_rand(200,255),mt_rand(200,255));

//填充背景色
imagefill($img,0,0,$bg);

//循环写入
for($i = 0;$i < 4;$i++){
    //分配文字颜色
    $txt = imagecolorallocate($img,mt_rand(50,150),mt_rand(50,150),mt_rand(50,150));

    //写入文字
    imagestring($img,mt_rand(1,5),60 + $i*20,90,$captcha[$i],$txt);
}

//输出
header(&#39;Content-type:image/png&#39;);
imagepng($img);

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

4. Chinese verification code

Two points to note
Get random Chinese: In PHP In Chinese, data is operated in units of bytes. Chinese has different numbers of bytes in different character sets.
Chinese writing function: imagettftext(image resource, font size, font rotation angle, font starting X, font starting Y, font file, content, color);

1. Create canvas: fill the background color

2. Get random Chinese

3.Write Chinese to the picture

4. Save the output image

5. Destroy resources

//中文验证码
header(&#39;Content-type:text/html;charset=utf-8&#39;);

//创建画布
$img = imagecreatetruecolor(200,200);
//给背景分配颜色
$bg = imagecolorallocate($img,mt_rand(200,255),mt_rand(200,255),mt_rand(200,255));
//填充背景色
imagefill($img,0,0,$bg);

//写入内容
for($i = 0;$i < 4;$i++){
    //分配颜色
    $txt = imagecolorallocate($img,mt_rand(50,150),mt_rand(50,150),mt_rand(50,150));

    //获取随机中文
    $string = "今天我寒夜里看雪飘过怀着冷却了的心窝飘远方";
    
    $pos = mt_rand(0,strlen($string) - 1);
    $start = $pos - $pos % 3;        //utf-8取模3,GBK取模2

    //取三个长度(字符串截取)
    $target = substr($string,$start,3);

    //写入中文
    imagettftext($img,mt_rand(20,40),mt_rand(-45,45),40 + $i * 30, mt_rand(80,120),$txt,&#39;simple.ttf&#39;,$target);

}

//输出图片
header(&#39;Content-type:image/png&#39;);
imagepng($img);

//销毁资源
imagedestroy($img);

5. Encapsulation verification code class

//验证码工具类

class Captcha{
    //属性
    private $width;
    private $height;
    private $strlen;
    private $lines;     //干扰线数量
    private $stars;     //干扰点数量
    private $font;      //字体路径

    //构造方法:初始化属性
    public function __construct($info = array()){
        //初始化属性
        $this->width    = isset($info[&#39;width&#39;])?$info[&#39;width&#39;]:146;
        $this->height    = isset($info[&#39;height&#39;])?$info[&#39;height&#39;]:23;
        $this->strlen    = isset($info[&#39;strlen&#39;])?$info[&#39;strlen&#39;]:4;
        $this->lines    = isset($info[&#39;lines&#39;])?$info[&#39;lines&#39;]:10;
        $this->stars    = isset($info[&#39;stars&#39;])?$info[&#39;stars&#39;]:50;
        $this->font        = isset($info[&#39;font&#39;])?$info[&#39;font&#39;]:&#39;fonts/AxureHandwriting-BoldItalic.otf&#39;;
    }

    //生成验证码图片
    public function generate(){
        //创建画布,给定背景色
        $img = imagecreatetruecolor($this->width,$this->height);
        $c_bg = imagecolorallocate($img,mt_rand(200,255),mt_rand(200,255),mt_rand(200,255));
        imagefill($img,0,0,$c_bg);

        //写入字符串
        $captcha = $this->getStr();
        
        //增加干扰点"*"
        for($i = 0;$i < $this->stars;$i++){
            //随机颜色
            $c_star = imagecolorallocate($img,mt_rand(100,150),mt_rand(100,150),mt_rand(100,150));

            //写入*号
            imagestring($img,mt_rand(1,5),mt_rand(0,$this->width),mt_rand(0,$this->height),&#39;*&#39;,$c_star);
        }

        //增加干扰线
        for($i = 0;$i < $this->lines;$i++){
            //随机颜色
            $c_line = imagecolorallocate($img,mt_rand(150,200),mt_rand(150,200),mt_rand(150,200));

            //划线
            imageline($img,mt_rand(0,$this->width),mt_rand(0,$this->height),mt_rand(0,$this->width),mt_rand(0,$this->height),$c_line);
        }

        //随机颜色
        for($i = 0;$i < $this->strlen;$i++){
            $c_str = imagecolorallocate($img,mt_rand(0,100),mt_rand(0,100),mt_rand(0,100));
            imagettftext($img,mt_rand(10,20),mt_rand(-45,45),20 + $i * 30,mt_rand(14,$this->height - 6),$c_str,$this->font,$captcha[$i]);

        }
        
        //输出图片
        header(&#39;Content-type:image/png&#39;);
        imagepng($img);

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

    //获取随机字符串
    //@return 字符串
    private function getStr(){
        //ASCII码表生成字符串
        $str = &#39;&#39;;

        //循环生成
        for($i = 0;$i < $this->strlen;$i++){
            //随机选择数字,小写字母和大写字母
            switch(mt_rand(0,2)){
                case 0: //数字
                    $str .= chr(mt_rand(49,57));
                    break;
                case 1: //小写字母
                    $str .= chr(mt_rand(97,122));
                    break;
                case 2: //大写字母
                    $str .= chr(mt_rand(65,90));
                    break;
            }
        }

        //将验证码字符串保存到session
        $_SESSION[&#39;captcha&#39;] = $str;

        //返回结果
        return $str;
    }

    /*
     * 验证验证码
     * @param1 string $captcha,用户输入的验证码数据
     * @return boolean,成功返回true,失败返回false
     */
    public static function checkCaptcha($captcha){
        //与session中的验证码进行验证

        //验证码不区分大小写
        return (strtoupper($captcha) === strtoupper($_SESSION[&#39;captcha&#39;]));
    }

}

Recommended learning: "PHP Video Tutorial

The above is the detailed content of How to implement image verification code in php. For more information, please follow other related articles on the PHP Chinese website!

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