繁体   English   中英

无法在zip(php)中添加所有文件

[英]Can't add all files in the zip (php)

因此,我在互联网上找到了可以将文件放入zip的此类。 我有一个可以将图片上传到文件夹的表单,但是当我尝试将它们添加到zip时,我只能添加该文件夹中的最后一个文件(循环)。

拉链类

<?php

class zipper {
    private $_files = array(),
            $_zip;

    public function __construct() {
        $this->_zip = new ZipArchive;
    }


    public function add($input){
        if(is_array($input)){
            $this->_files = array_merge($this->_files, $input);
        }else{
            $this->_files[] = $input;
        }

    }
        public function store($location = null){

            if(count($this->_files) && $location){
                foreach ($this->_files as $index => $file) {
                    if(!file_exists($file)){
                        unset($this->_files[$index]);
                    }
                    print_r($file . "<br>");// here gives me the exact path of the files.
                }

                if($this->_zip->open($location, file_exists($location) ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE)){
                    foreach ($this->_files as $file) {
                        $this->_zip->addFile($file, $file);
                    }

                    $this->_zip->close();
                }
            }

        }
}

这是我的上传文件

> $uniqUser = uniqid(strtoupper($userName). "-" , true); 
> $directory ='../upload/';  
> $file_name is $files['name']

if(!is_dir("../upload/". $uniqUser ."/")) {
                    mkdir("../upload/". $uniqUser ."/");
                }


                if(move_uploaded_file($file_tmp, $directory .  $uniqUser . "/" . $file_name)){
                    $uploaded[$position] = $directory . $uniqUser . "/" . $file_name;
                        $zipper = new zipper;
                        $zipper->add(BASE_URL . "/upload/" . $uniqUser . "/" . $file_name);
                        $zipper->store(BASE_URL . "/upload/" . $uniqUser . ".zip");

最后一个代码位于foreach内部,该循环循环到上载的文件中。

当我执行print_r("Added file:" . $file . "<br>"); 查看是否添加了所有文件,我得到了肯定的答复。 但是我总是从文件夹中获取最后一个文件。 谢谢

编辑好吧,猜猜问题出在每个循环之后,将文件添加到文件夹中,zip类将文件添加到zip中,然后在检查zip是否存在之后... ...因此,在每个循环之后,zip被覆盖并添加仅最后一个文件。 我怎样才能使它更好?

问题有点愚蠢……我不得不在foreach $zipper = new zipper;之外创建类$zipper = new zipper; 和$ zipper- store("../upload/" . $uniqUser . ".zip"); 进行不必要的重复(在底部添加)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM