php生成验证码,注重细节

以前生成验证码的文件掉了,又只有重新写一个。有以下优点:

1、文字大小可以设置,我随便复制了一个windows的arial.ttf字体

2、随机字符没有大写,因为有些字母大小写分不清楚;

3、去掉了数字0和1,以及字母的o和l,同理它们容易混淆,用户体验不好。

header("Content-type:image/png");
        $num = 4; //字符个数
        $width = 70; // 图像宽度
        $height = 40; // 图像高度
        $size = 16;  // 文字大小
        $str = "abcdefghijkmnpqrstuvwxyz23456789"; //随机字符
        $code = "";
        for ($i = 0; $i < $num; $i++) {
            $code .= substr($str, rand(0, strlen($str) - 1), 1);
        }
         $_SESSION["validate_code"] = $code; //改成你自己的session键
        //创建图片
        $im = imagecreate($width, $height);
        //填充背景
        $bg_color = imagecolorallocate($im, rand(200,255), rand(200,255), rand(200,255));
        imagefill($im, 0, 0, $bg_color);
        //干扰点
        for($m = 0; $m <= 100; $m++){
            $point_color=imagecolorallocate($im, rand(0,255), rand(0,255), rand(0,255));
            imagesetpixel($im, rand(0, $width - 1), rand(0, $height - 1), $point_color);
        }
        //干扰线
        for ($i = 0;$i <= 4;$i++){
            $line_color = imagecolorallocate($im, rand(0,255), rand(0,255), rand(0,255));
            imageline($im, rand(0,$width), rand(0,$height), rand(0,$width), rand(0,$height), $line_color);
        }
        $rand_x = rand(1, 6);
        for ($i = 0; $i < $num; $i++) {
            $font_color = imagecolorallocate($im, rand(0,120), rand(0,120), rand(0,120));
            // imagestring($im, 5, $strx, $strpos, substr($code, $i, 1), $font_color); //缺点是字体大小不能控制
            // imagettftext ( resource $image , float $size , float $angle , int $x , int $y , int $color , string $font_file , string $text )
            @imagettftext($im, $size, rand(-15, 15), $rand_x, 20 + rand(0,8), $font_color, '/font/arial.ttf', substr($code, $i, 1)); // 换成你自己的字体文件物理路径
            $rand_x += 16 + rand(0, 2);
        }
        imagepng($im);
        imagedestroy($im);

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值