首页 > 后端开发 > php教程 > 如何使用 PHP 压缩整个文件夹并选择性地删除其内容?

如何使用 PHP 压缩整个文件夹并选择性地删除其内容?

Barbara Streisand
发布: 2024-12-27 10:22:11
原创
750 人浏览过

How to Zip a Complete Folder and Optionally Delete Its Contents Using PHP?

使用 PHP 压缩整个文件夹

问题:

如何使用 PHP 创建整个文件夹的 ZIP 存档PHP?另外,如何在压缩后删除文件夹中的所有内容(不包括特定文件)?

答案:

1.压缩整个文件夹:

$rootPath = rtrim($rootPath, '\/');
$rootPath = realpath('folder-to-zip');

$zip = new ZipArchive();
$zip->open('file.zip', ZipArchive::CREATE | ZipArchive::OVERWRITE);

$files = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator($rootPath),
    RecursiveIteratorIterator::LEAVES_ONLY
);

foreach ($files as $file) {
    if (!$file->isDir()) {
        $filePath = $file->getRealPath();
        $relativePath = substr($filePath, strlen($rootPath) + 1);

        $zip->addFile($filePath, $relativePath);
    }
}

$zip->close();
登录后复制

2。压缩整个文件夹删除除“important.txt”之外的所有文件:

$rootPath = rtrim($rootPath, '\/');
$rootPath = realpath('folder-to-zip');

$zip = new ZipArchive();
$zip->open('file.zip', ZipArchive::CREATE | ZipArchive::OVERWRITE);

$filesToDelete = array();

$files = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator($rootPath),
    RecursiveIteratorIterator::LEAVES_ONLY
);

foreach ($files as $file) {
    if (!$file->isDir()) {
        $filePath = $file->getRealPath();
        $relativePath = substr($filePath, strlen($rootPath) + 1);

        $zip->addFile($filePath, $relativePath);

        if ($file->getFilename() != 'important.txt') {
            $filesToDelete[] = $filePath;
        }
    }
}

$zip->close();

foreach ($filesToDelete as $file) {
    unlink($file);
}
登录后复制

以上是如何使用 PHP 压缩整个文件夹并选择性地删除其内容?的详细内容。更多信息请关注PHP中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板