Search code examples
phpziparchive

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


So I found this class on the internet that can put files into a zip. I have a form where I can upload pictures into a folder, but when I try to add them into the zip I could add only the last file from that folder (loop).

zipper class

<?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();
                }
            }

        }
}

and this is my uploading file

> $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");

the last code is inside a foreach that loops into the files uploaded.

When I did a print_r("Added file:" . $file . "<br>"); to see if the all files are added, I get a positive response. But I always get the last file from the folder. Thank you

EDIT Well, Guess the problem is after each loop to add the files in the folder, the zip class adds the file into the zip, then after checks if the zip exists or no ... So after each loop the zip is overwritten and adds only the last file. How can I make this better ?


Solution

  • The problem was kinda stupid ... I had to create the class outside the foreach $zipper = new zipper; and $zipper-store("../upload/" . $uniqUser . ".zip");for unnecessary repeating (added it at the bottom).