驗證碼圖片顯示紅叉(斷裂圖標)通常因HTTP響應體被污染(輸出了非圖片數據)或Header錯誤。本文提供系統排查清單、最小可運行代碼、常見框架集成注意事項。
<?php
// captcha.php - 獨立文件,無任何include/require
session_start(); // 必須最先調用
$len = 4;
$code = '';
for ($i = 0; $i < $len; $i++) {
$code .= dechex(mt_rand(0, 15));
}
$_SESSION['captcha'] = strtolower($code);
$width = 100; $height = 35;
$img = imagecreatetruecolor($width, $height);
// 背景白
$white = imagecolorallocate($img, 255, 255, 255);
imagefill($img, 0, 0, $white);
// 干擾線
for ($i = 0; $i < 6; $i++) {
$color = imagecolorallocate($img, mt_rand(0, 200), mt_rand(0, 200), mt_rand(0, 200));
imageline($img, mt_rand(0, $width), mt_rand(0, $height), mt_rand(0, $width), mt_rand(0, $height), $color);
}
// 干擾點
for ($i = 0; $i < 50; $i++) {
$color = imagecolorallocate($img, mt_rand(150, 255), mt_rand(150, 255), mt_rand(150, 255));
imagesetpixel($img, mt_rand(0, $width), mt_rand(0, $height), $color);
}
// 繪製字符
for ($i = 0; $i < $len; $i++) {
$color = imagecolorallocate($img, mt_rand(0, 100), mt_rand(0, 100), mt_rand(0, 100));
$x = $i * ($width / $len) + mt_rand(5, 15);
$y = mt_rand(5, $height / 2);
imagestring($img, 5, $x, $y, $code[$i], $color);
}
// 關鍵:輸出前確保無任何輸出
header('Content-Type: image/png');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache');
imagepng($img);
imagedestroy($img);
| # | 現象/原因 | 檢查方法 | 解決 |
|---|---|---|---|
| 1 | 文件開頭有BOM頭(UTF-8 with BOM) | 用十六進制編輯器查看文件前3字節 EF BB BF | IDE設置「UTF-8 without BOM」保存 |
| 2 | 前有空白/換行 | 文件首字符必須是< | 刪除所有前導空白 |
| 3 | 包含文件尾部?>後有空白/換行 | 檢查所有include文件 | **所有PHP文件省略結尾?>** |
| 4 | 錯誤/警告輸出混入圖片流 | 臨時開啟error_reporting(E_ALL); ini_set('display_errors',1);訪問圖片URL看報錯 | 修復錯誤或error_reporting(0)生產環境 |
| 5 | session_start()在輸出後調用 | 檢查調用順序 | 移至文件最頂部 |
| 6 | GD庫未安裝/未啟用 | php -m | grep gd 或 phpinfo() | 安裝php-gd,extension=gd |
| 7 | Header發送後又有輸出 | 檢查imagepng()後是否有echo/var_dump | 確保imagepng是最後執行語句 |
| 8 | 輸出緩衝未刷新/衝突 | 框架中可能已開啟ob_start | 在輸出前ob_clean()或ob_end_clean() |
Response::make($pngContent, 200, ['Content-Type' => 'image/png'])而非直接header。web中間件組外(避免Session/CSRF中間件干擾),或標記為stateless。Cache::put('captcha:' . $key, $code, 600)而非Session,支持分佈式、無Cookie場景。composer require gregwar/captcha
// 控制器
use Gregwar\Captcha\CaptchaBuilder;
$builder = new CaptchaBuilder();
$builder->build();
$builder->save('php://output', 'png');
session(['captcha' => $builder->getPhrase()]);
系統化排查+BOM頭/結束標簽/輸出緩衝三大鐵律,徹底解決驗證碼紅叉問題。