Create and Download ZIP file with PHP

zip-box-example

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.

Demo Download

PHP code

This is the PHP code to create a zip files and then add files to the archive.

$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.

Tags: |

Deepanker Verma is the founder of Techlomedia. He is a tech blogger, developer and gadget freak.


Similar Articles

0 Comments

Leave a comment

Comment policy: We love comments and appreciate the time that readers spend to share ideas and give feedback. However, all comments are manually moderated and those deemed to be spam or solely promotional will be deleted.

2020 UseThisTip | Part of Techlomedia Internet Pvt Ltd Developed By Deepanker