美文网首页
验证码完整版封装,有备注,可供多模式选择

验证码完整版封装,有备注,可供多模式选择

作者: 孤岛渔夫 | 来源:发表于2016-12-04 01:53 被阅读0次
    <?php 
    // 验证码
    
    /**
     * [yzm 验证码]
     * @param  integer $width    [验证码画布宽度]
     * @param  integer $height   [验证码画布高度]
     * @param  integer $length   [验证码个数]
     * @param  integer $type     [验证码类型]
     *                         1: 纯数字
     *                         2: 小写字母
     *                         3: 数字字母混合
     * @param  string  $img_type [图片格式]
     */
    function yzm($width=160, $height=50, $length=4, $type=1, $img_type='png'){
    // 1.创建真彩图
        $img = imagecreatetruecolor($width,$height);
    // 2.分配颜色
        $back = imagecolorallocate($img, mt_rand(130,255),mt_rand(130,255),mt_rand(130,255));
        $font_color = imagecolorallocate($img, mt_rand(0,120),mt_rand(0,120),mt_rand(0,120));
    // 3.填充颜色
        imagefill($img, 0,0, $back);
    // 4.画图
        switch($type){
            case '1': $str = implode(array_rand(array_flip(range('0','9')),$length));
                break;
            case '2': 
                $str = implode(array_rand(array_flip(range('a','z')),$length));
                break;
            case '3': 
                // ord()   返回字符对应的ASCII值
                // chr()   返回ASCII值对应字符
                //  a: 97
                //  z: 122
                //  A: 65
                //  Z: 90
                //  0: 48
                //  9: 57
                $str = '';

                for($j=0; $j<$length; $j++){
                    //  随机获取一个类型的字符
                    $num = mt_rand(1,3);
                    switch($num){
                        case '1': $str .= chr(mt_rand(48,57)); break;
                        case '2': $str .= chr(mt_rand(65,90)); break;
                        case '3': $str .= chr(mt_rand(97,122)); break;
                    }
                }

                break;
        }
        
        // 将产生的字符写入SESSION中, 未来会用到
        $_SESSION['v_code'] = $str;

        // 画干扰点
        for($i = 0; $i < 500; $i++){
            imagesetpixel($img, mt_rand(0,$width), mt_rand(0,$height), darkColor($img));
        }


        // 将画布平均分成4份
        $w = $width/$length;

        for($i=0; $i<$length; $i++){
            $x = $i*$w + 20;        
            $y = mt_rand(20,$height-20);
            imagettftext($img, 15, mt_rand(0,90) ,$x,$y,  $font_color, 'Arvo-Regular.ttf', $str[$i]);
        }

    // 5.保存或者输出图片
        header('content-type:image/'.$img_type);
        $func = 'image'.$img_type;
        $func($img);

    // 6.销毁资源
        imagedestroy($img);
    }

    function darkColor($img){
        return imagecolorallocate($img, mt_rand(0,120),mt_rand(0,120),mt_rand(0,120));
    }

    yzm(200,80,4,3,'gif');





 ?>

相关文章

网友评论

      本文标题:验证码完整版封装,有备注,可供多模式选择

      本文链接:https://www.haomeiwen.com/subject/sefhmttx.html