php创建没有zip文件路径的zip文件 [英] php creating zips without path to files inside the zip

查看:31
本文介绍了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文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆