file - How to zip a whole directory and download using php -
this question has answer here:
i self studying php , creating sample test site lets user input file code used determine file path of folder downloaded. code have below download single file. want download , zip whole directory. please help. thank in advance
<h3>search client file</h3> <form method="post" action="#" id="searchform"> type image code:<br><br> <input type="text" name="icode"> <br> <input type="submit" name="submit" value="search"> </form> <?php $fcode=$_post["icode"]; if (!empty($fcode)) { $file="/var/www/website/$fcode.tif"; if (file_exists($file)) { header('content-description: file transfer'); header('content-type: application/octet-stream'); header('content-disposition: attachment; filename='.basename($file)); header('content-transfer-encoding: binary'); header('expires: 0'); header('cache-control: must-revalidate'); header('pragma: public'); header('content-length: ' . filesize($file)); ob_clean(); ob_end_flush(); readfile($file); } else { echo "the file $fcode.tif not exist"; } } else { echo "no values"; } ?>
<?php $dir = 'dir'; $zip_file = 'file.zip'; // real path our folder $rootpath = realpath($dir); // initialize archive object $zip = new ziparchive(); $zip->open($zip_file, ziparchive::create | ziparchive::overwrite); // create recursive directory iterator /** @var splfileinfo[] $files */ $files = new recursiveiteratoriterator( new recursivedirectoryiterator($rootpath), recursiveiteratoriterator::leaves_only ); foreach ($files $name => $file) { // skip directories (they added automatically) if (!$file->isdir()) { // real , relative path current file $filepath = $file->getrealpath(); $relativepath = substr($filepath, strlen($rootpath) + 1); // add current file archive $zip->addfile($filepath, $relativepath); } } // zip archive created after closing object $zip->close(); header('content-description: file transfer'); header('content-type: application/octet-stream'); header('content-disposition: attachment; filename='.basename($zip_file)); header('content-transfer-encoding: binary'); header('expires: 0'); header('cache-control: must-revalidate'); header('pragma: public'); header('content-length: ' . filesize($zip_file)); readfile($zip_file); ?>
read more at:
Comments
Post a Comment