I'm trying to make php download a .zip file using this code:
header('Content-Type: application/zip');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Content-Length: ' . filesize($file));
readfile($file);
$file is right.
I have two problem with this script:
If I use header('Content-Length: ' . filesize($file));
the download is corrupt with 0 bytes file. If I comment this line, the download looks good on ubuntu.
If I use mac OS to download this file, after opening the .zip it extracts .cpgz file (for what I read is when the zip is corrupt)
I've tried all kind of headers to make this work, but the problem is always on that header. My question is: how can I make this work on all OS?
I use this for the purpose of downloading any kind of file using one generic PHP-script:
$base = "/path/to/downloadable/files";
$file = "myArchive.zip"; // or anything else
if(file_exists($base.$file)){
header('Content-Description: Download');
header('Content-Type: '.mime_content_type($base.$file));
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Content-Transfer-Encoding: binary');
header('Connection: Keep-Alive');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Content-Length: ' . filesize($base.$file));
echo file_get_contents($base.$file);
}
This works fine for me with almost every kind of file (including .zip).
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.