简体   繁体   中英

PHP Downloading zip created with ziparchive

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

: filesize(): stat failed for ../test.zip in on line :filesize():第行的/var/---///---/----/control/ajax/zipAJAX.php中统计信息失败

: readfile(../test.zip): failed to open stream: No such file or directory in on line :readfile(../ test.zip):无法打开流: 没有此类文件或目录行的

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.

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