
In this post, i will explain the PHP code to create a zip file of some files on a folder and then download it. You can add as many files as you wish. If you want users to select files to download, you can create a form for that. This is a simple code which shows how to create and add files to zip.
PHP code
This is the PHP code to create a zip files and then add files to the archive.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
$error = ""; //error holder if(isset($_POST['download'])){ $post = $_POST; $file_folder = "files/"; // folder to load files if(extension_loaded('zip')){ // Checking ZIP extension is available // Checking files are selected $zip = new ZipArchive(); // Load zip library $zip_name = time().".zip"; // Zip name if($zip->open($zip_name, ZIPARCHIVE::CREATE)!==TRUE) { // Opening zip file to load files $error .= "* Sorry ZIP creation failed at this time<br/>"; } $zip->addFile('files/webtips.docx'); // Adding files into zip $zip->close(); if(file_exists($zip_name)){ // push to download the zip header('Content-type: application/zip'); header('Content-Disposition: attachment; filename="'.$zip_name.'"'); readfile($zip_name); // remove zip file is exists in temp path unlink($zip_name); } }else $error .= "* You dont have ZIP extension<br/>"; } |
I have only added a single docx file. You can add as many files in the ZIP as you wish.
advertisement