扫盲 2026.10.05 10:09 37 次浏览 0 条评论

PHP压缩打包文件思路

PHP压缩打包,最省事用 ZipArchive。思路:先 new,open 建 zip,再遍历目录,把文件按相对路径 addFile,最后 close。

小皮面板下先确认 php_zip 扩展开了。路径用 realpath,Windows 的反斜杠换成 /,中文名一般不用管。

$zip = new ZipArchive();
$zip->open('bak.zip', ZipArchive::CREATE | ZipArchive::OVERWRITE);
$dir = realpath('./upload');
$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir));
foreach ($files as $file) {
    if ($file->isFile()) {
        $path = str_replace('\\', '/', $file->getPathname());
        $local = str_replace(str_replace('\\', '/', $dir) . '/', '', $path);
        $zip->addFile($path, $local); // 文件按相对路径进压缩包
    }
}
$zip->close();

空目录想保留就加 addEmptyDir。压缩大目录注意 PHP 超时和目录权限。

标签:PHP,压缩打包,ZipArchive

说点什么 0

行思随记

欢迎来到:行思随记