我有一个函数可以在传递一个工作得很漂亮的文件数组时创建zip文件。
$zip_file = create_zip($_FILES['myfile']['tmp_name'],$target);
但是,所发生的是zip存档中的文件都具有tmp名称而没有扩展名。改变我传递给函数的数组的最佳方法是什么,以便文件的命名方式与上传时相同?
答案 0 :(得分:3)
我已重写create_zip
以包含localnames
参数。传递$_FILES['myfile']['name']
以获取文件的原始名称。
function create_zip($files = array(),$localnames=array(),$destination = '',$overwrite = false) {
//if the zip file already exists and overwrite is false, return false
if(file_exists($destination) && !$overwrite) { return false; }
//vars
$valid_files = array();
//if files were passed in...
if(is_array($files)) {
//cycle through each file
foreach($files as $file) {
//make sure the file exists
if(file_exists($file)) {
$valid_files[] = $file;
}
}
}
//if we have good files...
if(count($valid_files)) {
//create the archive
$zip = new ZipArchive();
if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
return false;
}
//add the files to archive
for ($i = 0; $i < count($valid_files); $i++) {
$zip->addFile($valid_files[$i],$localnames[$i]);
}
//debug
//echo 'The zip archive contains ',$zip->numFiles,' files with a status of ',$zip->status;
//close the zip -- done!
$zip->close();
//check to make sure the file exists
return file_exists($destination);
}
else
{
return false;
}
}
用法:
$zip_file = create_zip($_FILES['myfile']['tmp_name'], $_FILES['myfile']['name'],
$target);