在zip档案中正确命名文件的最佳方式


Best way to properly name files within zip archive

我有一个函数,当传递一个运行良好的文件数组时,它会创建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);