Here's what I'm trying to do. I have a series of reports that they also want to be able to download as comma delimited text files. I've read over a bunch of pages where people say simply echo out.
If you are trying to download multiple files at the same time and downloading the files one by one, then there is a better option to create a zip file, add the downloading files in the zip and download the zip file. Using PHP, this is very easy. PHP ZipArchive()
class provides all functionality to create a zip file with multiple files. You need PHP 5.2.0 and higher for that class.
Create Zip File
- First thing you have to fix a path and a name for the zip file. The zip file will create in that location with the name, so choose a suitable location in your project folder. If you are working on WordPress custom plugin, then select the path in your custom plugin folder.
- Now create the Zip Archive and open the zip file. If the
$zip->open()
does not returntrue
, then there is some problem, so exit with some message - Add files in the Zip file. To add any file, we can add the file using the file path or we can add the file using its contents.
1st parameter is the full path of the file with the file name and file extension.
2nd parameter is for file name inside the zip file, if it supplied then the original file name will be overridden.
Now add file using its contents.
- Now don’t forget to close the zip file.
Download the Created Zip File
Now the file is ready for download. You know the created xip file location and name so you can add a tag for download the zip file or you can force download using PHP for automatic download.
Generate File To Download Php Installer
- For force download, you have to set the header correctly. When you are setting the header for download the Zip file that time <coce>Content-type and
Content-Disposition
correctly. InContent-Disposition
, add the attachment, it will suggest the browser to download the file instead of displaying it directly. - Now the header is set, so clear the output buffer before downloading the Zip file. Sometimes, the download Zip file does not open correctly and in Safari, the auto unzipping also failed for some reason. To avoid the problem, you need to clean the output buffer.
- Now download the Zip file in your local.
- The Zip file location and name is always the same, so how many times the functionality executes every time the new file will be added in the same Zip file, so keeping the created Zip file after download complete is just a waste of disk space, so delete the Zip file after download. If you need to keep the created Zip file all the time, that time doesn’t use
unlink()
, just change the Zip file name every time, such that add the time with the file name. - Last but not the least, don’t forget to exit after
readfile()
.