PHP makes a zip file of 2 string variables

So what I'm trying to do is take 2 lines and create 2 files. Then create a zip from these files and let the 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.

+5
source share
3 answers

You missed the most important part - the output of the file! :)

Add

readfile('test.zip');

to the end of the php file.


Also, the HTTP content length header is not computed correctly:

header("Content-Length: ".filesize($zip));

This will always give you 0 (or false), since filesize expects the file name as an argument.

Change the line to:

header("Content-Length: ".filesize('test.zip'));

After that, both files will load successfully and contain two files. For completeness, here is a complete 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');
+8
source

PHP ( , , ).

filesize() , . filesize ($ filename) .

:

error_reporting (E_ALL | E_STRICT); ini_set ('display_errors', 1);

php.ini

+1

After all the calls to header (), I think you want:

readfile($filename); 
+1
source

All Articles