发布日期:2018-03-26
如何使用PHP压缩整个文件夹?+ 查看更多
如何使用PHP压缩整个文件夹?
+ 查看更多
发布日期:2018-03-10 15:53
分类:PHP
浏览次数:121
我已经在Stack Overflow网站上找到一些关于如何压缩特定文件的程序代码,但如何压缩一个特定的文件夹呢?
Folder/ index.html picture.jpg important.txt
在我的文件夹中有许多文件。在压缩了整个文件夹之后,我想删除文件夹中除了“important.txt”文件之外的所有内容。
在stack上找到这个问题,我需要你的帮助,谢谢。
回答
以下代码更新于2015年4月22日。
压缩一个完整的文件夹,代码如下:// 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();
压缩一个完整的文件夹,并删除除了“important.txt”文件之外的所有文件,代码如下:
// 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); // Initialize empty "delete list" $filesToDelete = array(); // 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); // Add current file to "delete list" // delete it later cause ZipArchive create archive only after calling close function and ZipArchive lock files until archive created) if ($file->getFilename() != 'important.txt') { $filesToDelete[] = $filePath; } } } // Zip archive will be created only after closing object $zip->close(); // Delete all files from "delete list" foreach ($filesToDelete as $file) { unlink($file); }