【发布时间】:2016-06-07 11:41:21
【问题描述】:
我对一个简单的 PHP 代码有一个奇怪的行为。当我尝试使用正确的内容类型强制下载或打印图像时,输出文件已损坏。
似乎网络服务器 (apache) 在文件开头添加了两个字节(0x20 和 0x0A)。
这是代码:
$file = "image.png";
$image = file_get_contents($file);
// Test
file_put_contents("test.png", $image);
// Download
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file));
echo $image;
我在同一台服务器上托管的其他网站上使用相同的代码没有问题。
问题仅在下载时出现,因为 test.png 可以正常工作。 text.png 的 MD5 校验和与原图相等。
这是 test.png 的十六进制代码。
这是下载后损坏文件的十六进制代码:
如您所见,开头有 2 个额外字节。如果我删除它们,文件将恢复正常工作。
我附上Wireshark的屏幕(如你所见不是浏览器问题):
我该如何解决?
服务器是带有 PHP-5.6 的 Ubuntu 16.04(是的,我已经从 7.0 降级到 5.6 以解决与 roundcube 的兼容性问题)
更新 1:我正在尝试查找文件中的某处是否有空格 + 换行符
更新 2:
首先:谢谢。
代码是 Wordpress 插件的一部分,下载是使用 AJAX 系统调用的。我写了一个简单的插件测试:
<?php
/*
Plugin Name: Test
Plugin URI: http://www.google.com
Description: Test
Author: Anon
Version: 4.0
*/
function downlod_test() {
echo "test";
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=prova.html');
die();
}
function iopman_shared_download_doc_ajax() {
downlod_test();
}
add_action('wp_ajax_frontend_download_doc', 'iopman_shared_download_doc_ajax');
//downlod_test();
?>
如果我使用 /wp-admin/admin-ajax.php?action=frontend_download_doc 调用 downlod_test,它会添加 2 个额外字节。如果我直接调用它(通过删除 cmets),它可以工作。
那么现在的问题是:如何去掉wordpress添加的这些字节?
【问题讨论】:
-
x20 是一个空格,x0A 是一个换行符(又名
\n)。也许这可以帮助您弄清楚它的来源。您显示的代码不应生成它们。 -
如何剥离它们?使用 get_included_files()、debug_print_backtrace() 找到它们,然后在编辑器中加载文件并删除它们。
标签: php image corruption corrupt