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

查看:165
本文介绍了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.

是否可以将压缩包中的文件减去所有文件夹?

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 (字符串 $ filename [,字符串 $ 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天全站免登陆