首页 > php用header('content-type: image/png')输出验证码,但响应回来的是text/html

php用header('content-type: image/png')输出验证码,但响应回来的是text/html

<?php
header("Content-type: image/png");
session_start();
$image = imagecreatetruecolor(70,30);
$bgcolor = imagecolorallocate($image,255,255,255);
imagefill($image,0,0,$bgcolor);

// 生成干扰像素点
for ($i=0; $i < 200; $i++) {
    $pixelcolor = imagecolorallocate($image,rand(121,254),rand(121,254),rand(121,254));
    imagesetpixel($image,rand(1,69),rand(1,29),$pixelcolor);
}

    // 生成干扰直线
for ($i=0; $i < 4; $i++) {
    $linecolor = imagecolorallocate($image,rand(121,254),rand(121,254),rand(121,254));
    imageline($image,rand(0,69),rand(0,29),rand(0,69),rand(0,29),$linecolor);
}

$captch_code = "";
// 生成验证码
for ($i=0; $i < 4; $i++) {
    $fontsize = 6;
    $fontcolor = imagecolorallocate($image,rand(0,120),rand(0,120),rand(0,120));
    $data = 'abcdefghijkmnpqrstuvwxy3456789';
    $fontcontent = substr($data,rand(0,strlen($data)-1),1);
    $captch_code .= $fontcontent;
    $x = ($i*70/4)+rand(5,10);
    $y = rand(5,10);
    imagestring($image,$fontsize,$x,$y,$fontcontent,$fontcolor);
}
$_SESSION['authcode'] = $captch_code;
imagepng($image);
imagedestroy($image);

上面为生成验证码的代码,在本地服务器可以生成验证码,但把代码上传到远程服务器后就无法生成验证码,返回500(intetnal server error)错误,远程服务器已开启GD库,代码开头header('content-type: image/png'),但响应回来的却是text/html。


远程服务器返回text/html


本地成功返回image/png


1- 远端服务器没有开启php的错误输出,此时当致命错误发生的时候直接返回web server 500错误,需要开启错误输出或查看php的错误日志获知具体错误。
2- 不应该在代码的开始处使用header('image/png');而是应该将该行移到imagepng($image);之前,否则就算有错误信息也会由于错误的头导致无法看到正确的结果。


控制台点那个500看具体错误响应内容,如果没有开启错误打印


都500错误了你还想啥呢?


出错了,没有执行到header png这一块的逻辑


感觉是500错误后,没有调用到header("Content-type: image/png");
因为500错误本身就要返回的是一些错误文本,因此就成text/html了

【热门文章】
【热门文章】