0
votes

I am new to PHP and am trying to create ZIP function which is called through ajax and downloaded to the user. I get a positive response with the zip but the streaming gives me an error for filesize():stat failed for ../test.zip and also read file failed to open stream, no such file or directory on the php page. Here is my code below - I have seared pretty hard and can't seem to find an answer that makes sens for my situation

    <?php
    require("../../common.php");
    ini_set('display_startup_errors',1);
    ini_set('display_errors',1);
    error_reporting(-1);
$thisdir = " ";
$zip = new ZipArchive();
$filename = "../test.zip";
if ($zip->open($filename, ZipArchive::CREATE)!==TRUE) {
    exit("cannot open <$filename>\n");
}
$zip->addFromString('insert.pdf' . time(), "#1 This is a test string added as testfilephp.txt.\n");;
$zip->addFile($filename . "../../../folder/pdf_folder/");
echo "numfiles: " . $zip->numFiles . "\n";
echo "status:" . $zip->status . "\n";
echo $filename;
//$size = filesize($zip->filename);
$zip->close();
header("Content-type: application/zip"); 
header("Content-Disposition: attachment; filename=$filename");
header("Content-length: " . filesize($filename));
header("Pragma: no-cache"); 
header("Expires: 0"); 
readfile("$filename");
?>

thank you for any help or guidance

****** edit here is the error for the code

Warning: filesize(): stat failed for ../test.zip in /var/---/----/---/----/control/ajax/zipAJAX.php on line 21

Warning: readfile(../test.zip): failed to open stream: No such file or directory in /var/---/----/---/----/control/ajax/zipAJAX.php on line 24

1
Could you copy the error message and stack trace to the question?ren.rocks
What is this? $zip->addFile('../test.zip../../../folder/pdf_folder/')? Should be two args separated by a comma? Also I don't like the $filename and $zip->filename inconsistencies/duality - maybe just avoid it, I get you were probably debugging.ficuscr

1 Answers

0
votes

You can't add the contents of a folder to a zip file with the addFile method. You have to loop the directory (http://php.net/dir) and add each file to your zip with the addFile method.

Before you send any data back to the user, you can check if the zip file exists.

$zip->close();
if(file_exists($file)) {
  header("Content-type: application/zip"); 
  header("Content-Disposition: attachment; filename=$filename");
  header("Content-length: " . filesize($filename));
  header("Pragma: no-cache"); 
  header("Expires: 0"); 
  readfile("$filename");
}

Also check that the user has write permission in the directory where you want to place the zip file.