So what I am trying to do is take 2 strings and create 2 files. Then create a zip out of these files and let a user download them.
Here is what I have:
$string1 = 'Some data some data some data';
$string2 = 'Some data some data some data';
$zip = new ZipArchive();
$filename = "test.zip";
if ($zip->open($filename, ZIPARCHIVE::CREATE)!==TRUE) {
exit("cannot open <$filename>\n");
}
$zip->addFromString("string1.txt", $string1);
$zip->addFromString("string2.txt", $string2);
$zip->close();
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"".$filename."\"");
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".filesize('test.zip'));
So far no luck. Any help is appreciated.
You missed the most important part - output the file! :)
Add:
readfile('test.zip');
to the end of the php file.
Also the calculation of the HTTP content-length header is wrong:
header("Content-Length: ".filesize($zip));
This will give you always 0 ( or false) as filesize expects a filename as its argument.
Change the line to:
header("Content-Length: ".filesize('test.zip'));
After doing both of this the zip will successfully download and contains the two files. For completenes, here comes the full working example:
$string1 = 'Some data some data some data';
$string2 = 'Some data some data some data';
$zip = new ZipArchive();
$filename = "test.zip";
if ($zip->open($filename, ZIPARCHIVE::CREATE)!==TRUE) {
exit("cannot open <$filename>\n");
}
$zip->addFromString("string1.txt", $string1);
$zip->addFromString("string2.txt", $string1);
$zip->close();
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"".$filename."\"");
header("Content-Transfer-Encoding: binary");
// make sure the file size isn't cached
clearstatcache();
header("Content-Length: ".filesize('test.zip'));
// output the file
readfile('test.zip');
You have a PHP error (you probably dont have error reporting turned on or high enough error level).
the filesize() function takes a string not an object. filesize($filename) will work.
to turn on error reporting do:
error_reporting(E_ALL|E_STRICT); ini_set('display_errors', 1);
alternatively do this in php.ini
After all those header() calls, I think you want:
readfile($filename);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With