t4fewq 发表于 2014-9-25 09:20:29

PHP用GD库绘制图片,制作验证码浏览器不能输出

1,代码如下:
<?php   
        function fillRandomString(){
                //生成验证码
                $char = array_merge(range(0, 9),range("a", "z"),range("A", "Z"));
                //讲字符串$char打乱
                $luan = str_shuffle(implode("", $char));
                //从字符串中随机取四位
                returnsubstr($luan, 0,4 );
        }
                //创建画布
                header('content-type:image/png');
                $height = 20;
                $width = 80;
                $image = imagecreate($width, $height);
                $black = imagecolorallocate($image, 0, 0, 0);
                $white = imagecolorallocate($image, 255, 255, 255);
                //画图片矩形
                imagefilledrectangle($image, 1, 1, $width-2, $height-2, $white);
                //填充字符串
                imagestring($image, 20, 20,4, fillRandomString(), $black);
                //输出图片
               imagepng($image);
               
               //销毁图片
               imagedestroy($image);

但是在浏览器上输出显示不了,原因是在向浏览器输出之前没有清理缓存
在header()之前加入代码 ob_clean();即可

页: [1]
查看完整版本: PHP用GD库绘制图片,制作验证码浏览器不能输出