首页 > 解决方案 > 在 php 上下载时重命名 zip 中的文件

问题描述

我有一些问题要问,我如何下载 zip 并使用一些 php 代码重命名 zip 中的文件?这是我的代码:

$file_path='../../files_pangkat/';
$file_names[0] = $ck_sk_terakhir[file_pangkat];
$zip = new ZipArchive();

//create the file and throw the error if unsuccessful
if ($zip->open($archive_file_name, ZIPARCHIVE::CREATE )!==TRUE) {
    exit("cannot open <$archive_file_name>\n");
}

//add each files of $file_name array to archive
$zip->addFile($file_path.$file_names[0],$file_names[0]);
$zip->renameName($file_names[0], 'SK_PNS_'.$c_bio[nip_baru].'pdf');
echo $file_path.$file_names[0],$file_names[0]."<br />";
$zip->close();

//then send the headers to foce download the zip file 
header("Content-type: application/zip"); 
header("Content-Disposition: attachment; filename=$archive_file_name");  
header("Pragma: no-cache"); 
header("Expires: 0"); 
readfile("$archive_file_name");
unlink("$archive_file_name");
exit;

$file_names是我保存在数据库中的文件名,但是当我使用时$zip->renameName(),它不起作用..

标签: php

解决方案


首先将文件添加到 zip 文件中,然后立即重命名新添加的文件,这似乎没有多大意义。

相反,您应该使用您想要的名称添加文件,另请参阅addFile().

所以你应该改变:

$zip->addFile($file_path.$file_names[0],$file_names[0]);
$zip->renameName($file_names[0], 'SK_PNS_'.$c_bio[nip_baru].'pdf');

至:

$zip->addFile($file_path . $file_names[0], 'SK_PNS_' . $c_bio[nip_baru] . 'pdf');

推荐阅读