php中 为什么验证码 必须要开启 ob_clean 才可以显示?

用ob_clean(),将前面的输出都清除就OK了

这表示你的程序前面有输出,<?php 前有空格、空行、文件有BOM头

ob_clean();
header("content-type: image/jpeg");

//生成验证码
$char = '1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ';
$len = 4;
$schar = '';
$charlen = strlen($char);

for ($i=0; $i < $len; $i++) { 
    $schar .= $char[rand(0,$charlen)];
}

//将结果保存到 session中
@session_start();
$_SESSION['captcha_code'] = $schar;


//读取图片
$bg_file = './captcha/captcha_bg' . mt_rand(1,5) . '.jpg';
//根据图片创建画布
$img = imagecreatefromjpeg($bg_file);

if (rand(1,2) == 1) {
  $color = imagecolorallocate($img, 0, 0, 0 );
}else {
  $color = imagecolorallocate($img, 255, 255, 255);
}

$imgsize = getimagesize($bg_file);



imagestring($img, 5, 30, 0, $schar,$color );

imagepng($img);

imagedestroy($img);