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).examdb
和 setup/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 的基名是您想要传递给它的内容(我假设现在您正在传递某种相对路径)
请记住,您必须手动断言您的文件名是唯一的。
参见
关于php - 在 php 中从不同位置制作文件的 Zip 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9666917/