You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WordPress中压缩指定目录时如何仅保留目标文件夹及其内容,排除上级路径

WordPress中压缩指定目录时如何仅保留目标文件夹及其内容,排除上级路径

看起来你遇到的问题是ZipArchive默认会把文件的完整绝对路径打包进去,想要只保留files文件夹本身和它的子内容对吧?我帮你梳理下问题所在,然后给出修正后的代码。

首先看你代码里的几个小问题:

  • 你定义了$source变量,但后面误用了未定义的$sourceRelativePath,这明显是笔误;
  • 在处理文件路径时,没有正确计算文件相对于$source目录的相对路径,导致绝对路径被直接打包进zip。

接下来是具体的修正方案,我会把完整的修正代码和细节说明一起给你:

$student = $student_first_name .'-'. $student_last_name.'_'.$student_id;

$upload_dir = wp_upload_dir();  

// 确认source指向files目录的绝对路径
$source = $upload_dir['basedir'] . "/student-records/" . $student . "/files/";
// 用basedir确保zip文件路径指向正确的学生目录,避免依赖path的月份目录特性
$zipFile = $upload_dir['basedir'] . "/student-records/" . $student . "/{$student}.zip";

// Initialize archive object
$zipArchive = new ZipArchive();

# Create a zip target
if( $zipArchive->open( $zipFile, ZipArchive::CREATE | ZipArchive::OVERWRITE ) !== TRUE ) {
    exit("Unable to open file.");
}           

// 先确认source是有效目录
if (is_dir($source)) {
    // 创建递归目录迭代器,自动跳过.和..目录
    $files = new RecursiveIteratorIterator(
        new RecursiveDirectoryIterator($source, RecursiveDirectoryIterator::SKIP_DOTS),
        RecursiveIteratorIterator::SELF_FIRST
    );          

    foreach ($files as $file) { 
        $filePath = str_replace('\\', '/', $file->getRealPath());
        // 计算当前文件相对于source目录的相对路径,这就是它在zip里的路径
        $relativePath = substr($filePath, strlen($source));

        if (is_dir($file)) {
            // 向zip添加空目录,用相对路径保证结构正确
            $zipArchive->addEmptyDir($relativePath . '/');
        } else if (is_file($file)) {
            // 用addFile更高效,直接关联本地文件到zip内的相对路径
            $zipArchive->addFile($filePath, $relativePath);
            // 如果你希望zip内保留files文件夹作为根目录,就把上面的relativePath改成:
            // $relativePath = 'files/' . substr($filePath, strlen($source));
        }
    }
} else if (is_file($source)) {
    $zipArchive->addFromString(basename($source), file_get_contents($source));
}

$zipArchive->close();

// 生成可公开访问的下载链接(把本地路径转成web URL)
$zipFileURL = str_replace($upload_dir['basedir'], $upload_dir['baseurl'], $zipFile);
echo '<a href="'.$zipFileURL.'" target="_blank"><span class="dashicons dashicons-download"></span> Download</a>';

额外补充几个细节说明:

  1. 我把$zipFile的路径改成了基于basedir,因为wp_upload_dir()的path是当前月份的上传目录,这里用basedir更稳妥,能保证zip文件直接存在学生的专属目录下;
  2. 生成下载链接时,必须把本地的basedir替换成web可访问的baseurl,否则前端会拿到无效的本地文件路径;
  3. 用addFile()替代你原来的addFromString(),不需要把文件内容读入内存,性能更优。

如果你的需求是zip打开后先看到files文件夹,再进入查看内部的Application、Transcripts,只需要按代码注释里的提示修改$relativePath的生成逻辑即可。

备注:内容来源于stack exchange,提问作者Jan Bantolinay

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.15 09:33:02