Handling zip file download completion and cancellation event in PHP

|
| By Webner

Handling zip file download completion and cancellation event (PHP)

Problem: I am working on a project in which user needs to download a zip file from the website. I am creating zip file on the server temporarily which should be deleted after download or if operation is cancelled by the user. However I have found the solution to resolve this which is given below.

Steps:
1. I am using ZipArchive to create a zip file to download. I will add an image file in the zip file which will be downloaded by the user. Below code will create a zip file

$zip_file = 'path_of_the_file/zipFile.zip';
$zip = new ZipArchive();
$zip->open($zip_file , ZipArchive::CREATE)

2. Now add below lines to the code which are adding image file to the zip file. In this we are adding file from local path.

$zip->addFile(‘path_of_the_file’,’file_name’);
$zip->close();

Don’t forget to close the zip. Now zip file is ready to download.

3. You can force download of the zip file using php but you need to set the headers properly. You need to set Content-Type and Content-Disposition correctly. In Content-Disposition, set attachment, it will suggest the browser to download the file instead of displaying it directly.

header('Content-type: application/zip');
header('Content-Disposition: attachment; filename="'.basename($zip_file).'"');
header("Content-length: " . filesize($zip_file));
header("Pragma: no-cache");
header("Expires: 0");

4. Now header is set. Now you need to clear the output buffer because sometimes it does not open properly. Avoid that by adding below code.

ob_clean();
flush();

5. Now write below code to download the created zip file.

readfile($zip_file);

6. To delete the file after download completion or cancellation, add below code:

ignore_user_abort(true);
unlink($zip_file);

Function ignore_user_abort(true) will continue to execute the script (rest of the php code) even if the user has cancelled the download process. It will handle the cancel event of the file. By default, parameter of this function is set to FALSE which means after user aborts the process, the php script will also abort.

7. Function unlink($file_name) will delete the file after completely downloaded or cancelled by the user.

8. Don’t forget to exit the script.

exit();

Leave a Reply

Your email address will not be published. Required fields are marked *