Hello Readers,
This post helps you to create a ZIP file using PHP.
<form name="zip" method="post">
<input type="checkbox" name="files[]" value="book.pdf" />
<input type="checkbox" name="files[]" value="doc.pdf" />
<input type="submit" name="createpdf" value="Download" />
<input type="reset" name="reset" value="Reset" />
</form>
$error = "";
if(isset($_POST['createpdf']))
{
$post = $_POST['createpdf'];
$file_folder = "files/"; // folder to save files
if(extension_loaded('zip'))
{
// Checking ZIP extension is available
if(isset($post['files']) and count($post['files']) > 0)
{
$zip = new ZipArchive(); // Load zip library
$zip_name = time().".zip";
if($zip->open($zip_name, ZIPARCHIVE::CREATE)!==True)
{
// check for error
$error .= "Sorry ZIP creation failed";
}
foreach($post['files'] as $file)
{
$zip->addFile($file_folder.$file); // Adding files into zip
}
$zip->close();
if(file_exists($zip_name))
{
header('Content-type: application/zip');
header('Content-Disposition: attachment; filename="'.$zip_name.'"');
readfile($zip_name);
unlink($zip_name);
}
}
else
$error .= "Please select file to zip ";
}
else
$error .= "You dont have ZIP extension";
}
In the above code, we used Html form with post method and the as a input we use checkbox which contain the name as an array variables. After that use the php code to post the form in the same page.
Here, the main function is:
$zip = new ZipArchive() which is used to load the zip library and we mention in comment what other line do in this code
0 Comment(s)