php验证码类

    function verifyImage($width=78, $height=26, $type=1, $len=4, $sessName='verify', $lines=4, $pixels=30)
    {
        session_start();        //开启session
        $image = imagecreatetruecolor($width, $height);            //创建画布
        $bg = imagecolorallocate($image, 255, 255, 255);        //背景色

        imagefilledrectangle($image, 1, 1, $width - 2, $height - 2, $bg);        //画布填充

        $str = '';
        for($i = 0; $i < $len; $i++)            //获取验证码
        {
            switch ($type) {
                case 1:
                    $str .= range(0, 9)[mt_rand(0, count(range(0, 9)) - 1)];
                    break;
                case 1:
                    $str .= rand(0, 1) ? range(0, 9)[mt_rand(0, count(range(0, 9)) - 1)] : range('a', 'z')[mt_rand(0, count(range('a', 'z')) - 1)];
                    break;
                default:
                    break;
            }
        }
        $_SESSION[$sessName] = $str;            //写入session
        $fontfiles = array('msyh.ttf', 'msyhbd.ttf');

        for($i = 0; $i < $len; $i++)            //画布写入验证码
        {
            $size = mt_rand(14, 20);            //字体规格
            $angle = mt_rand(-30, 30);            //角度
            $x = mt_rand(4, 8) + $i * $size;    //x坐标
            $y = mt_rand($height - 8, $height - 4);    //y坐标
            $color = imagecolorallocate($image, mt_rand(20, 180), mt_rand(40, 200), mt_rand(60, 220));    //字体色
            $text = substr($str, $i, 1);        //字
            $fontfile = $fontfiles[mt_rand(0, count($fontfiles) - 1)];    //字体

            imagettftext($image, $size, $angle, $x, $y, $color, $fontfile, $text);
        }

        if($lines)                                //干扰线
        {
            for($i = 0; $i < $lines; $i++)
            {
                $color = imagecolorallocate($image, mt_rand(20, 180), mt_rand(40, 200), mt_rand(60, 220));
                imageline($image, mt_rand(0, $width - 1), mt_rand(0, $height - 1), mt_rand(0, $width - 1), mt_rand(0, $height - 1), $color);
            }
        }

        if($pixels)                                //干扰点
        {
            for($i = 0; $i < $pixels; $i++)
            {
                $color = imagecolorallocate($image, mt_rand(20, 180), mt_rand(40, 200), mt_rand(60, 220));
                imagesetpixel($image, mt_rand(0, $width - 1), mt_rand(0, $height - 1), $color);
            }
        }

        header('Content-type:image/gif');
        imagegif($image);
        imagedestroy($image);

    }

你可能感兴趣的:(PHP,Verify,验证码类)