John Davidson

download - Zip content is cleared after downloading it in php

0 comments
Message:


The Problem is that when downloading the zip, its content gets deleted.
I use this code to create the zip and add the files to it:


    $zipName = "full path";
$zip = new ZipArchive();
$zip->open($zipName, ZipArchive::CREATE);
for ($i = 0; $i < $length; $i++) {
if ($ausgabeArray[$i]["filePath"] != '') {
$zip->addFromString(basename($ausgabeArray[$i]["filePath"]), file_get_contents($ausgabeArray[$i]["filePath"]));
}
}
$zip->close();
for ($i = 0; $i < $length; $i++) {
unlink($ausgabeArray[$i]["filePath"]);
}

And I use this code to download the zip:


        header("Content-disposition: attachment; filename=" . $name);
header("Content-type: application/".$endung);
readfile($path);
unlink($path);
//name = basename from the path of the zip
//path = full path to the zip
//endung = zip

This worked fine on the old server, but after changing it, it stopped working. I stopped the code once before readfile($path); and viewed the zip in the folder and downloaded it from there, everything worked fine this way, but this is of course no option for anybody who has no permission for the server directories.


We use this server:



  1. Ubuntu 20.04.2 LTS

  2. Apache/2.4.41 (Ubuntu)

  3. 7.3.29 FPM-Application


I'm not sure if the problem has anything to do with the server change or just my code, but I didn't change a thing, and now it is not working any more, so I think it is possible.
I hope someone had this problem before and can help me. Thanks!



My Answer:
"example.zip";
$zip = new ZipArchive;
if ($zip->open($zipName, ZipArchive::CREATE) === TRUE) {
$files = array("file1.txt", "file2.txt", "file3.txt");
foreach ($files as $file) {
$zip->addFile($file);
}
$zip->close();
} else {
echo "Failed to create zip file";
}

header('Content-Type: application/zip');
header('Content-Disposition: attachment; filename="' . $zipName . '"');
readfile($zipName);

// Delete the zip file after downloading
unlink($zipName);

Rate this post

4 of 5 based on 9358 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us