php 创建 zip,但没有 zip 内文件的路径
我正在尝试使用 php 创建一个 zip 文件(它确实如此 - 取自此页面 - http:// /davidwalsh.name/create-zip-php),但是 zip 文件内部包含文件本身的所有文件夹名称。
是否可以仅将 zip 中的文件减去所有文件夹?
这是我的代码:
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');
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.
Is it possible to just have the file inside the zip minus all the folders?
Here's my code:
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');
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这里的问题是
$zip->addFile
传递了相同的两个参数。根据文档:
这意味着第一个参数是文件系统中实际文件的路径,第二个参数是路径和路径。文件在存档中的文件名。
当您提供第二个参数时,您需要在将其添加到 zip 存档时从中删除路径。例如,在基于 Unix 的系统上,这看起来像:
The problem here is that
$zip->addFile
is being passed the same two parameters.According to the documentation:
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.
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:
我认为更好的选择是:
它只是从路径中提取文件名。
I think a better option would be:
Which simply extracts the filename from the path.
这只是我发现对我有用的另一种方法
This is just another method that I found that worked for me
我用它来从 zip 中删除根文件夹,该文件夹
将位于 zip 中:
我们的代码:
I use this to remove root folder from zip
wil be in zip:
our code: