Today we discuss how to create a zip file from a folder of images and download it from the browser. As result, we will have all the files in a folder archived to a zip file and downloaded to our computer.
Important to realize we use built-in PHP class ZipArchive
to achieve this. ZipArchive
Class which allows us to create a Zip file. This class makes file creation easier.
Contents
- HTML Form & PHP
- Bootstrap
- Download
HTML & PHP
As with other tutorials on the website we use Twitter bootstrap to create scaffolding for the little application, which is easier and understandable for all people.
<!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Bootstrap CSS --> <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous"> <title>Hello, world!</title> </head> <body> <div class="col-5 mx-auto"> <h1>Download Zip File from a folder</h1> <h3>Files in the folders</h3> <?php $files = scandir('./images'); foreach($files as $file) { if($file == '.' || $file == '..') continue; print "<img src='./images/".$file."' width='100' class='mb-4'>"; print "<br>"; } ?> <form action="download.php" method="post"> <button type="submit" class="btn btn-info">Download Zip</button> </form> </div> <!-- Optional JavaScript; choose one of the two! --> <!-- Option 1: Bootstrap Bundle with Popper --> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script> </body> </html>
Create and download the Zip file
When the beautiful form submits, it triggers the download.php file and as a first step, it creates the zip file, and then with the help of PHP force download headers, it will download the file to your computer.
<?php $zipFile = "images.zip"; // Initializing PHP class $zip = new ZipArchive(); $zip->open($zipFile, ZipArchive::CREATE | ZipArchive::OVERWRITE); $files = scandir('./images'); foreach($files as $file) { if($file == '.' || $file == '..') continue; $zip->addFile('./images/'.$file, $file); } $zip->close(); //Force download a file in php if (file_exists($zipFile)) { header('Content-Description: File Transfer'); header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename="' . basename($zipFile) . '"'); header('Expires: 0'); header('Cache-Control: must-revalidate'); header('Pragma: public'); header('Content-Length: ' . filesize($zipFile)); readfile($zipFile); exit; } ?>
Leave a Reply