Tags
Asked 2 years ago
30 Jun 2021
Views 259
Eulalia

Eulalia posted

How to create a ZIP file using PHP and delete it after user

How to create a ZIP file using PHP and delete it after user
ching

ching
answered May 4 '23 00:00

To create a ZIP file using PHP, we can use the ZipArchive class that is built into PHP. Here's an example of how we can create a ZIP file and add files to it:



$zip = new ZipArchive();
$filename = "files.zip";

if ($zip->open($filename, ZipArchive::CREATE) === TRUE) {
  $zip->addFile("file1.txt");
  $zip->addFile("file2.txt");
  $zip->addFile("file3.txt");
  $zip->close();
  // Download the ZIP file
  header('Content-Type: application/zip');
  header('Content-disposition: attachment; filename=' . $filename);
  header('Content-Length: ' . filesize($filename));
  readfile($filename);
  // Delete the ZIP file
  unlink($filename);
} else {
  echo "Failed to create ZIP file";
}

In the example above, we first create a new instance of the ZipArchive class and specify the name of the ZIP file we want to create. We then use the addFile() method to add files to the ZIP file.

After we've added all the files, we close the ZIP file and set the headers to force the user's browser to download the ZIP file. We then use the unlink() function to delete the ZIP file from the server.

When the user downloads the ZIP file, it will be automatically deleted from the server. This ensures that the server doesn't get cluttered with unnecessary files.

Post Answer