Today i am sharing how to create a zip file of multiple files using PHP and download that zip file on click. For this purpose i will need a folder where all files are available which can be selected and downloaded. I will also create a single php page which contain the following scripts.
HTML
Create a simple PHP page and copy paste the below form.
|
<form name="zips" action="" method="post">
<input type="checkbox" id="checkAll" />
<label>Select All</label><br />
<input class="chk" type="checkbox" name="files[]" value="SampleFile.pdf"/>
<label>PDF File</label><br />
<input class="chk" type="checkbox" name="files[]" value="SampleFile.docx"/>
<label>Word File</label><br />
<input class="chk" type="checkbox" name="files[]" value="AllPHPTricks.png"/>
<label>Image File</label><br />
<input type="submit" id="submit" name="createzip" value="Download All Seleted Files" >
</form>
|
jQuery
Add the following script in footer of web page. Don’t forget to add jQuery library before this script.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
$('#submit').prop("disabled", true);
$("#checkAll").change(function () {
$("input:checkbox").prop('checked', $(this).prop("checked"));
$('#submit').prop("disabled", false);
if ($('.chk').filter(':checked').length < 1){
$('#submit').attr('disabled',true);}
});
$('input:checkbox').click(function() {
if ($(this).is(':checked')) {
$('#submit').prop("disabled", false);
} else {
if ($('.chk').filter(':checked').length < 1){
$('#submit').attr('disabled',true);}
}
});
|
PHP
Copy paste the below PHP script in the top of web page. When someone submit form first we are checking if files array is set or not, then we are creating zip file and downloading that file.
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
|
<?php
if(isset($_POST['files']))
{
$error = ""; //error holder
if(isset($_POST['createzip']))
{
$post = $_POST;
$file_folder = "files/"; // folder to load files
if(extension_loaded('zip'))
{
// Checking ZIP extension is available
if(isset($post['files']) and count($post['files']) > 0)
{
// 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";
}
foreach($post['files'] as $file)
{
$zip->addFile($file_folder.$file); // 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 .= "* Please select file to zip ";
}
else
$error .= "* You dont have ZIP extension";
}
}
?>
|
If you found this tutorial helpful so share it with your friends, developer groups and leave your comment.
No comments:
Post a Comment