php - 在 php 中从不同位置制作文件的 Zip 文件

标签 php zip

function create_zip($files = 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

foreach($valid_files as $file) {

  $zip->addFile($file,$file);

}

//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;

}

}

// using function as

include('functions.php');

$files_to_zip = array(

'database/350-001(3.1).examdb',

'setup/ExaminationEngine.exe'

);

//if true, good; if false, zip creation failed

$result = create_zip($files_to_zip,'my-archive.zip');

我正在使用这个函数来制作zip。

一切都工作完美,但在 zip 文件下创建的文件是由完整路径创建的,我只需要 my-archive.php 中的两个文件。但在 my-archive.php datbase/350-001(3.1).examdbsetup/ExaminationEngine.exe 数据库和安装文件夹中创建。

我该如何解决这个问题?

最佳答案

尝试

//add the files
foreach($valid_files as $file) {
    $zip->addFile($file,basename($file));
}

而不是

//add the files
foreach($valid_files as $file) {
    $zip->addFile($file,$file); 
}

addFile 的第二个参数是“本地路径”,$file 的基名是您想要传递给它的内容(我假设现在您正在传递某种相对路径)

请记住,您必须手动断言您的文件名是唯一的。

参见

http://php.net/manual/en/ziparchive.addfile.php

http://php.net/manual/en/function.basename.php

关于php - 在 php 中从不同位置制作文件的 Zip 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9666917/

相关文章:

PHP 从 mysql 中提取每日平均值的平均值

java - Google Appengine JAVA - Zip 大量保存在 Blobstore 中的图片

java - 使用 Java ZipFile 类解压缩 ZIP 文件

java - ByteArrayOutputStream.toByteArray() 返回随机字节?

php - 查询返回不存在的行

php - 使用 MySQL 在 Android 登录页面上出现错误的用户名和密码

android - 如何使用 iOS 和 Android 的密码 (AES) 压缩文件?

git - Git 可以将 ZIP 文件视为目录并将 ZIP 内的文件视为 blob 吗?

php - 按 ID 查询数据库以获取页面标题和内容

php - 无法从 PHP 中的字符串中删除所有换行符