PHP笔记-验证码例子

2022/2/5 17:12:33

本文主要是介绍PHP笔记-验证码例子,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

注意需要先把php_gd2.dll放开:

php.ini文件修改。

如下验证码效果:

代码如下:

Captcha.php

<?php


namespace vendor;


class Captcha{

    public static function getCaptcha($width = 450, $height = 65, $length = 4, $fonts = ""){

        if(empty($fonts)){

            $fonts = 'captcha.ttf';
        }
        $fonts = __DIR__ . "/fonts/" . $fonts;

        $img = imagecreatetruecolor($width, $height);
        $bgColor = imagecolorallocate($img, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255));
        imagefill($img, 0, 0, $bgColor);

//        //增加干扰
        for($i = 0; $i < 50; $i++){

            $dotsColor = imagecolorallocate($img, mt_rand(140, 190), mt_rand(140, 190), mt_rand(140, 190));
            imagestring($img,mt_rand(1, 5), mt_rand(0, $width), mt_rand(0, $height), "*", $dotsColor);
        }

        for($i = 0; $i < 15; $i++){

            $lineColor = imagecolorallocate($img, mt_rand(80, 130), mt_rand(80, 130), mt_rand(80, 130));
            imageline($img, mt_rand(0, $width), mt_rand(0, $height), mt_rand(0, $width), mt_rand(0, $height), $lineColor);
        }
//
        $captcha = self::getString($length);
        @session_start();
        $_SESSION["captcha"] = $captcha;
        for($i = 0; $i < $length; $i++){

            $cColor = imagecolorallocate($img, mt_rand(15, 25), mt_rand(15, 25), mt_rand(15, 25));
            imagettftext($img, mt_rand(15, 25), mt_rand(-45, 45), $width / ($length + 1) * ($i + 1),
            mt_rand(25, $height -25), $cColor, $fonts, $captcha[$i]);
        }
        header("Content-type:image/png");
        imagepng($img);
        imagedestroy($img);
    }

    private static function getString($length = 4): string{

        $captcha = "";
        for($i = 0; $i < $length; $i++){

            switch(mt_rand(1, 3)){

                case 1: //49-57代表1-9
                    $captcha .= chr(mt_rand(49, 57));
                    break;
                case 2: //65-90代表a-z
                    $captcha .= chr(mt_rand(65, 90));
                    break;
                case 3: //97-122代表A-Z
                    $captcha .= chr(mt_rand(97, 122));
                    break;
            }
        }

        return $captcha;
    }

}

这里我的调用是这样的:

    public function captcha(){

        Captcha::getCaptcha();
    }

就可以了。



这篇关于PHP笔记-验证码例子的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程