如何在CakePhp中创建Zip文件并下载?

时间:2014-01-13 12:35:57

标签: php cakephp zip zipfile

我正在尝试使用CakePhp 1.3创建zip文件。文件描述存储在数据库中。在我的控制器中,我使用以下逻辑。

   // Fetching File description form database.     
   $this->view = 'Media';
   $user_id=$this->Session->read('userData.User.id');
   $condition = "Document.isdeleted = '0' AND Document.project_id='".  $project_id."'";
   $projectDocumentList = $this->Document->find("all",array('conditions'=>$condition,'fields'=>array('Document.id','Document.document_name','Document.path'),'order' => array('Document.id ASC')));
   $this->set('projectDocumentList',$projectDocumentList);
   if(!empty($projectDocumentList)){
   $fileNames = "";
   $fileNamesArr = array();
    foreach($projectDocumentList as $projectDocument){     
     $fileNamesArr[ ]= $projectDocument['Document']['document_name'];
    }
   }

   // Making zip
   $archive_file_name='myFile.zip';
   $file_path= "my_file_path";// Here I'm using my server basepath

   $zip = new ZipArchive();   
   if ($zip->open($archive_file_name, ZIPARCHIVE::CREATE )!==TRUE) {
    exit("cannot open <$archive_file_name>\n");
   }

   foreach($fileNamesArr as $files)
   {
   $zip->addFile($file_path.$files,$files);
   //echo $file_path.$files."<br>"; // This can show the file in browser
   }

   $zip->close();
   header("Content-type: application/zip");
   header("Content-Disposition: attachment; filename=$archive_file_name");
   header("Pragma: no-cache");
   header("Expires: 0");
   readfile("$archive_file_name");
   exit;

现在zip文件下载为myFile.zip,但是当我要打开该文件时,它会抛出错误“存档格式未知或已损坏”。

1 个答案:

答案 0 :(得分:2)

创建整个文件夹

的Zip文件
// Get real path for our folder
$rootPath = realpath('folder-to-zip');

// Initialize archive object
$zip = new ZipArchive();
$zip->open('file.zip', 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();

然后将zip文件的路径传递给视图。

$this->set('Zip_path'.zip_file_name);