无效的Zip文件下载(标题+ php)

时间:2016-05-02 21:26:29

标签: php header

我尝试通过标题下载zip文件:

$file = '/srv/users/serverpilot/apps/elm/public/dll/files/438de5/file-c117c93c.zip';
$filename = 'file-c117c93c.zip';
if (file_exists($file))
{
    $fileName = trim($filename);
    header('Content-Description: File Transfer');
    header('Content-Disposition: attachment; filename='.$fileName);
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    ob_clean();
    flush();
    readfile($file);
    exit;       
}

文件将以真实尺寸下载。但是当我打开下载的文件时,zip文件无法打开(无效的存档错误)

有什么不对?

1 个答案:

答案 0 :(得分:0)

在尝试了几个解决方案后,我意识到问题出在apache发送的Content-Encoding: gzip上。我的httpd.conf设置为默认发送此标头,这会导致文件下载出现问题:

HTTP/1.1 200 OK
Date: Mon, 02 May 2016 21:52:08 GMT
Server: Apache
x-powered-by: PHP/5.3.3
content-transfer-encoding: Binary
Content-Disposition: attachment; filename="peace.zip"
Vary: Accept-Encoding
Content-Encoding: gzip
Connection: close
Transfer-Encoding: chunked
Content-Type: application/zip

在另一台服务器上,返回的标头不包含Content-Encoding: gzip,您的代码可以正常运行。

HTTP/1.1 200 OK
Date: Mon, 02 May 2016 21:57:43 GMT
Server: Apache/2.2.15
x-powered-by: PHP/5.4.45
Content-Description: File Transfer
Content-Disposition: attachment; filename="peace.zip"
content-transfer-encoding: binary
Expires: 0
Cache-Control: must-revalidate
Pragma: public
Content-Length: 627874
Connection: close
Content-Type: application/zip

<强>解决方案:

我挣扎了大约1个小时...... 在php文件的开头添加以下内容:

apache_setenv('no-gzip', 1);
ini_set('zlib.output_compression', 0);

Voilá,强制下载工作......