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

PHP多文件URL下载打包ZIP,无法修改压缩包内文件名求助

解决压缩包内文件名无法修改的问题

我看了你的代码,核心问题在于你目前直接用basename($res)作为压缩包内的文件名,所以没法自定义。下面给你几个实用的修改方案,按需选择:

方案1:统一添加前缀/后缀

如果只是想给所有文件加个统一标识(比如前缀downloaded_),直接修改addFromString的第一个参数就行:

$zip = new ZipArchive();
$zip_name = time().".zip";
if($zip->open($zip_name, ZIPARCHIVE::CREATE)!==TRUE) {
    $error = "* Sorry ZIP creation failed at this time";
}else{
    foreach ($_POST as $file) {
        foreach($file as $res){
            $download_file = file_get_contents($res);
            // 自定义文件名:添加前缀
            $custom_filename = "downloaded_" . basename($res);
            $zip->addFromString($custom_filename, $download_file);
        }
    }
    $zip->close();
}

方案2:自定义每个文件的文件名

如果需要给每个文件单独指定新名字,你需要在前端提交时同时传递原文件URL和目标文件名(比如把$_POST结构改成包含url和new_name的数组),后端这样处理:

$zip = new ZipArchive();
$zip_name = time().".zip";
if($zip->open($zip_name, ZIPARCHIVE::CREATE)!==TRUE) {
    $error = "* Sorry ZIP creation failed at this time";
}else{
    // 假设$_POST的每个元素是包含url和new_name的关联数组
    foreach ($_POST['files'] as $file_data) {
        $res = $file_data['url'];
        $new_filename = $file_data['new_name'];
        // 安全处理:过滤掉路径,防止恶意路径遍历
        $new_filename = basename($new_filename);
        $download_file = file_get_contents($res);
        $zip->addFromString($new_filename, $download_file);
    }
    $zip->close();
}

方案3:批量替换文件名中的字符

如果需要批量修改文件名的某部分(比如替换下划线为横杠),用字符串处理函数就能搞定:

$zip = new ZipArchive();
$zip_name = time().".zip";
if($zip->open($zip_name, ZIPARCHIVE::CREATE)!==TRUE) {
    $error = "* Sorry ZIP creation failed at this time";
}else{
    foreach ($_POST as $file) {
        foreach($file as $res){
            $download_file = file_get_contents($res);
            $original_name = basename($res);
            // 替换文件名里的下划线为横杠
            $custom_filename = str_replace("_", "-", $original_name);
            $zip->addFromString($custom_filename, $download_file);
        }
    }
    $zip->close();
}

额外提醒

  • 用file_get_contents下载大文件可能会占用较多内存,大文件场景建议改用ZipArchive::addFile配合临时文件,或者用流的方式写入压缩包。
  • 一定要对自定义文件名做安全校验(比如用basename过滤),防止攻击者通过恶意文件名进行路径遍历攻击。

内容的提问来源于stack exchange,提问作者tst2016

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 03:33:06