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


invalid Zip file downloads (header+php)

我尝试通过头下载一个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文件无法打开(无效存档错误)

怎么了?

在尝试了几种解决方案后,我意识到问题出在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á,强制下载工作。。。