如何压缩整个目录并使用php下载

如何压缩整个目录并使用php下载

本文介绍了如何压缩整个目录并使用php下载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在自学php,正在创建一个示例测试站点,该站点允许用户输入文件代码,该文件代码将用于确定要下载的文件夹的文件路径。我下面的代码只会下载一个文件。我现在想要的是下载并压缩整个目录。请帮忙。预先谢谢您

I am self studying php and I am creating a sample test site which lets the user input the file code which will be used to determine the file path of the folder to be downloaded. The code i have below will only download a single file. What i want now is to download and zip the whole directory. Please help. Thank you in advance

    <h3>Search Client File</h3>
            <form  method="post" action="#"  id="searchform">
              Type the 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 does not exist";
      }
   }

     else
     {
       echo "No Values";
     }

    ?>


推荐答案

<?php

$dir = 'dir';
$zip_file = 'file.zip';

// Get real path for 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 as $name => $file)
{
    // Skip directories (they would be added automatically)
    if (!$file->isDir())
    {
        // Get real and relative path for current file
        $filePath = $file->getRealPath();
        $relativePath = substr($filePath, strlen($rootPath) + 1);

        // Add current file to archive
        $zip->addFile($filePath, $relativePath);
    }
}

// Zip archive will be created only 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);

?>

了解更多信息:

这篇关于如何压缩整个目录并使用php下载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 07:34