我有一个函数在传递一组精美的文件时创建zip文件。在zip压缩文件中正确命名文件的最佳方法
$zip_file = create_zip($_FILES['myfile']['tmp_name'],$target);
但是,会发生什么事情是zip文件中的文件都具有tmp名称并且没有扩展名。改变我传递给函数的数组的最佳方式是什么,以便文件的命名方式与上传时相同?
我有一个函数在传递一组精美的文件时创建zip文件。在zip压缩文件中正确命名文件的最佳方法
$zip_file = create_zip($_FILES['myfile']['tmp_name'],$target);
但是,会发生什么事情是zip文件中的文件都具有tmp名称并且没有扩展名。改变我传递给函数的数组的最佳方式是什么,以便文件的命名方式与上传时相同?
我已将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);
非常感谢!这正是我正在寻找的。 注意:对于任何其他使用此方法的人 - 在上面的代码[i]中应该替换为[$ i]以使其正常工作。 – 2012-03-24 22:36:15
@ aman88,真棒,很高兴帮助! (感谢您修复这个错误 - 没有引起足够的重视。) – benesch 2012-03-25 03:49:25
是[这](http://davidwalsh.name/create-zip-php)你'create_zip'? – benesch 2012-03-24 05:15:48
是的,就是这样。它需要一系列文件并返回一个存档。 – 2012-03-24 05:17:05