简体   繁体   中英

invalid Zip file downloads (header+php)

I try download a zip file via header:

$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;       
}

file will download with true size. but when I open downloaded file, zip file can not be open (invalid archive error)

what is the wrong?

After trying several solutions I realized the problem is on the Content-Encoding: gzip sent by apache. My httpd.conf is set to send this headers by default and this causes a problem on file downloads:

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

On a different server, the returning header doesn't contain Content-Encoding: gzip and your code works flawlessly.

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

Solution:

I've struggle for about 1 hour with this...
Add the following at the beginning of your php file:

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

Voilá, force download works...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM