Create Zip files and Download Zip file in PHP Code
Zip file downloading is used by websites. The most important and popular of theme is WordPress. They use Zip files for downloading plugins, themes and even their versions. They do it off course, dynamically. You just provide the location of the file and PHP will download it to the user for you. Actually HTTP headers have the main role in the downloading.
We make the headers using header function in PHP and the browser will take care of the rest. The file path that you provide must be the absolute path. These are the two variables where you provide information about the Zip file :
See also
Download Zip File
In this file we will download files in zip format. when we are check the checkbox and click on the download button then download the file in dynamically from database.
create_zip_download.php
<?php
// Database configuration
require "inc/config.php";
if (isset($_POST['submit'])) {
$ids = implode(",", $_POST['checkbox']);
$query = "SELECT * FROM `products` WHERE id IN ($ids)";
$reqult = $con->query($query);
//Files path
$filePath = 'images/';
$zipFileName = "myZipFile.zip";
if ($reqult->num_rows > 0) {
while ($row = $reqult->fetch_assoc()) {
$filename = $row['image'];
convertFileZipAndDownload($filename, $zipFileName, $filePath);
}
}
}
// CREATE FUNCTION FOR CREATE FILE IN ZIP AND DOWNLOAD
function convertFileZipAndDownload($fileNames, $zipFileName, $filePath)
{
$zip = new \ZipArchive();
//create the file and throw the error if unsuccessful
if ($zip->open($zipFileName, ZIPARCHIVE::CREATE )!==TRUE) {
exit("cannot open <$zipFileName>\n");
}
//add each files of $file_name array to archive
foreach($fileNames as $files)
{
$zip->addFile($filePath.$files,$files);
}
$zip->close();
//then send the headers to force download the zip file
if(!empty($zipFileName) && file_exists($filePath)){
// Define headers
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=$zipFileName");
header("Content-Type: application/zip");
header("Content-Transfer-Encoding: binary");
// Read the file
readfile($zipFileName);
exit;
}else{
echo 'The file does not exist.';
}
}
?>
FIND THE FULL ARTICLE ON DOWNLOAD ZIP FILE FROM DATABASE USING PHP CLICK ON THE BELOW LINK & ALSO FIND THE BEST ARTICLE ON THE BLOG SITE
https://webscodex.com/create-zip-files-and-download-zip-file-in-php-code/