[PHP GD库]⑦--验证码类封装

Captcha.php

<?php

class Captcha
{
    private $_fontfile = '';
    //字体大小
    private $_size = 20;
    //画布宽度
    private $_width = 120;
    //画布高度
    private $_height = 40;
    //验证码长度
    private $_length = 4;
    //画布资源
    private $_image = null;
    //干扰元素
    private $_snow = 0;
    private $_pixel = 0;
    private $_line = 0;

    public function __construct($config = array())
    {
        if (isset($config['fontfile']) && count($config) > 0) {
            if (isset($config['fontfile']) && is_file($config['fontfile']) && is_readable($config['fontfile'])) {
                $this->_fontfile = $config['fontfile'];
            } else {
                return false;
            }
            //检测是否设置字体大小
            if (isset($config['size']) && $config['size'] > 0) {
                $this->_size = (int)$config['size'];
            }
            //检测是否设置画布宽度
            if (isset($config['width']) && $config['width'] > 0) {
                $this->_width = (int)$config['width'];
            }
            //检测是否设置画布高度
            if (isset($config['height']) && $config['height'] > 0) {
                $this->_height = (int)$config['height'];
            }
            //检测是否设置验证码长度
            if (isset($config['length']) && $config['length'] > 0) {
                $this->_length = (int)$config['length'];
            }
            //配置干扰元素
            if (isset($config['pixel']) && $config['pixel'] > 0) {
                $this->_pixel = $config['pixel'];
            }
            if (isset($config['snow']) && $config['snow'] > 0) {
                $this->_snow = $config['snow'];
            }
            if (isset($config['line']) && $config['line'] > 0) {
                $this->_line = $config['line'];
            }

            $this->_image = imagecreatetruecolor($this->_width, $this->_height);
            return $this->_image;

        } else {
            return false;
        }
    }

    /**
     * 得到验证码
     * @return bool|string
     */
    public function getCaptcha()
    {
        $white = imagecolorallocate($this->_image, 255, 255, 255);
        imagefilledrectangle($this->_image, 0, 0, $this->_width, $this->_height, $white);
        //生成验证码
        $str = $this->_generateStr($this->_length);
        if (false == $str) {
            return false;
        }
        //绘制验证码
        $fontfile = $this->_fontfile;
        for ($i = 0; $i < $this->_length; $i++) {
            $size = $this->_size;
            $angle = mt_rand(-30, 30);
            $x = ceil($this->_width / $this->_length) * $i + mt_rand(5, 10);
            $y = ceil($this->_height / 1.5);
            $color = $this->_getRandColor();
            //$text = mb_substr($str, $i, 1, 'utf-8');
            $text = $str{$i};
            imagettftext($this->_image, $size, $angle, $x, $y, $color, $fontfile, $text);
        }

        //* -- 像素和线段
        if ($this->_snow) {
            $this->_getSnow();
        } else {
            if ($this->_pixel) {
                $this->_getPixel();
            }
            if ($this->_line) {
                $this->_getLine();
            }
        }

        //输出图像
        header('content-type:image/png');
        imagepng($this->_image);
        imagedestroy($this->_image);
        return strtolower($str);
    }

    private function _getSnow()
    {
        for ($i = 1; $i <= $this->_snow; $i++) {
            imagestring($this->_image, mt_rand(1, 5), mt_rand(0, $this->_width),
                mt_rand(0, $this->_height), '*', $this->_getRandColor());
        }
    }

    private function _getPixel()
    {
        for ($i = 1; $i <= $this->_pixel; $i++) {
            imagesetpixel($this->_image, mt_rand(0, $this->_width), mt_rand(0, $this->_height), $this->_getRandColor());
        }
    }

    /**
     * 绘制线段
     */
    private function _getLine()
    {
        for ($i = 1; $i <= $this->_line; $i++) {
            imageline($this->_image, mt_rand(0, $this->_width), mt_rand(0, $this->_height),
                mt_rand(0, $this->_width), mt_rand(0, $this->_height), $this->_getRandColor());
        }
    }


    /**
     * 产生验证码字符
     * @param int $length
     * @return bool|string
     */
    private function _generateStr($length = 4)
    {
        if ($length < 1 || $length > 30) {
            return false;
        }
        $chars = array('a', 'b', 'c', 'e', 'f', 'g', 'h', 'k', 'm', 'n', 'p', 'x', 'y', 'z',
            'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'K', 'M', 'N', 'P', 'X', 'Y', 'Z',
            1, 2, 3, 4, 5, 6, 7, 8, 9
        );
        $str = join('', array_rand(array_flip($chars), $length));
        return $str;
    }

    private function _getRandColor()
    {
        return imagecolorallocate($this->_image, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255));
    }

}

?>

testCaptcha.php

<?php
require_once 'Captcha.php';
$config = array(
    'fontfile' => 'fonts/couri.ttf',
    'pixel' => 20,
    'line' => 3
);
$captcha = new Captcha($config);
session_start();
$_SESSION['verifyName'] = $captcha->getCaptcha();

reg.php

<!DOCTYPE html>

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>注册页面</title>
</head>
<body>
<h1>IMOOC注册页面</h1>
<form action="doAction.php" method="post">
    <table bgcolor="#abcdef" width="80%" border="1" cellspacing="0" cellpadding="0">
        <tr>
            <td>用户名</td>
            <td><input type="text" name="username" id="" placeholder="请输入用户名..."></td>
        </tr>
        <tr>
            <td>密码</td>
            <td><input type="password" name="password" id="" placeholder="请输入密码..."></td>
        </tr>
        <tr>
            <td>验证码</td>
            <td><input type="text" name="vertify" id="" placeholder="请输入验证码">
                ![](testCaptcha.php)<a
                        onclick="document.getElementById('verifyImage').src='testCaptcha.php?r='+Math.random()"
                        href="javascript:void(0)">看不清,换一个</a>
            </td>
        </tr>
        <tr>
            <td colspan="2"><input type="submit" value="注册"></td>
        </tr>
    </table>
</form>

</body>

</html>

doAction.php

<?php
header("content-type:text/html;charset=utf-8");
session_start();
//print_r($_POST);
var_dump($_POST);
echo "<hr/>";
var_dump($_SESSION);
?>

Paste_Image.png
Paste_Image.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容