php creating zips without path to files inside the zip(php创建没有zip文件路径的zip文件)
问题描述
我正在尝试使用 php 创建一个 zip 文件(它确实这样做了 - 取自此页面 - http://davidwalsh.name/create-zip-php),但是在 zip 文件中包含文件本身的所有文件夹名称.
I'm trying to use php to create a zip file (which it does - taken from this page - http://davidwalsh.name/create-zip-php), however inside the zip file are all of the folder names to the file itself.
是否可以只将 zip 中的文件减去所有文件夹?
Is it possible to just have the file inside the zip minus all the folders?
这是我的代码:
function create_zip($files = array(), $destination = '', $overwrite = true) {
if(file_exists($destination) && !$overwrite) { return false; };
$valid_files = array();
if(is_array($files)) {
foreach($files as $file) {
if(file_exists($file)) {
$valid_files[] = $file;
};
};
};
if(count($valid_files)) {
$zip = new ZipArchive();
if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
return false;
};
foreach($valid_files as $file) {
$zip->addFile($file,$file);
};
$zip->close();
return file_exists($destination);
} else {
return false;
};
};
$files_to_zip = array('/media/138/file_01.jpg','/media/138/file_01.jpg','/media/138/file_01.jpg');
$result = create_zip($files_to_zip,'/...full_site_path.../downloads/138/138_files.zip');
推荐答案
这里的问题是 $zip->addFile
被传递了相同的两个参数.
The problem here is that $zip->addFile
is being passed the same two parameters.
根据文档:
bool ZipArchive::addFile ( string $filename [, string $localname ] )
bool ZipArchive::addFile ( string $filename [, string $localname ] )
文件名
要添加的文件的路径.
filename
The path to the file to add.
本地名称
ZIP 存档中的本地名称.
localname
local name inside ZIP archive.
这意味着第一个参数是文件系统中实际文件的路径,第二个是路径 &文件将在存档中的文件名.
This means that the first parameter is the path to the actual file in the filesystem and the second is the path & filename that the file will have in the archive.
当您提供第二个参数时,您需要在将其添加到 zip 存档时从中删除路径.例如,在基于 Unix 的系统上,这看起来像:
When you supply the second parameter, you'll want to strip the path from it when adding it to the zip archive. For example, on Unix-based systems this would look like:
$new_filename = substr($file,strrpos($file,'/') + 1);
$zip->addFile($file,$new_filename);
这篇关于php创建没有zip文件路径的zip文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:php创建没有zip文件路径的zip文件
基础教程推荐
- phpmyadmin 错误“#1062 - 密钥 1 的重复条目‘1’" 2022-01-01
- 在 yii2 中迁移时出现异常“找不到驱动程序" 2022-01-01
- 如何在 Symfony 和 Doctrine 中实现多对多和一对多? 2022-01-01
- HTTP 与 FTP 上传 2021-01-01
- PHP 守护进程/worker 环境 2022-01-01
- 如何在 XAMPP 上启用 mysqli? 2021-01-01
- 找不到类“AppHttpControllersDB",我也无法使用新模型 2022-01-01
- 在 CakePHP 2.0 中使用 Html Helper 时未定义的变量 2021-01-01
- 使用 PDO 转义列名 2021-01-01
- Doctrine 2 - 在多对多关系中记录更改 2022-01-01