Search code examples
phpdownloadzip

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


I need to download images from other websites to my server. Create a ZIP file with those images. automatically start download of created ZIP file. once download is complete the ZIP file and images should be deleted from my server.

Instead of automatic download, a download link is also fine. but other logic remains same.


Solution

  • Well, you'll have to first create the zipfile, using the ZipArchive class.

    Then, send :

    • The right headers, indicating to the browser it should download something as a zip -- see header() -- there is an example on that manual's page that should help
    • The content of the zip file, using readfile()

    And, finally, delete the zip file from your server, using unlink().


    Note : as a security precaution, it might be wise to have a PHP script running automatically *(by crontab, typically)*, that would delete the old zip files in your temporary directory.

    This just in case your normal PHP script is, sometimes, interrupted, and doesn't delete the temporary file.