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.
$zip_file = '(path_of_the_zip)/filename.zip';
If you are working on WordPress custom plugin, then select the path in your custom plugin folder.
$dir = plugin_dir_path( __FILE__ );
$zip_file = $dir . '/filename.zip';
- Now create the Zip Archive and open the zip file. If the
$zip->open()
does not return true
, then there is some problem, so exit with some message
$zip = new ZipArchive();
if ( $zip->open($zip_file, ZipArchive::CREATE) !== TRUE) {
exit("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.
$zip->addFile('full_path_of_the_file', 'custom_file_name');
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.
$download_file = file_get_contents( $file_url );
$zip->addFromString(basename($file_url),$download_file);
- Now don’t forget to close the zip file.
$zip->close();
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.