PHP手册包含以下示例:
<?PHP
// open the file in a binary mode
$name = './img/ok.png';
$fp = fopen($name, 'rb');
// send the right headers
header("Content-Type: image/png");
header("Content-Length: " . filesize($name));
// dump the picture and stop the script
fpassthru($fp);
exit;
?>
重要的是您必须发送Content-Type标头。另外,您必须注意不要在<?PHP ... ?>
标签之前或之后在文件中包含任何多余的空格(例如换行符)。
如注释中所建议,可以通过省略?>
标签来避免脚本末尾出现多余空格的危险:
<?PHP
$name = './img/ok.png';
$fp = fopen($name, 'rb');
header("Content-Type: image/png");
header("Content-Length: " . filesize($name));
fpassthru($fp);
您仍然需要小心避免在脚本顶部使用空格。一种特别棘手的空白形式是UTF-8BOM。为避免这种情况,请确保将脚本另存为“ ANSI”(记事本)或“ ASCII”或“ UTF-8无签名”(Emacs)或类似名称。