1

I am trying to create an archive of selected files using following code

$zip_in = new \ZipArchive;
if ($zip_in->open('input.zip') === TRUE) {
    $files = array();
    for ($loop = 0; $loop < $zip_in->numFiles; $loop++) {
        $files[] = $zip_in->getNameIndex($loop);
    }
    $zip_in->extractTo('workspace');
    $zip_in->close();
    /**
     * Changes done to files extracted inside WORKSPACE DIR above
     */
    chdir('workspace');
    $zip_out = new \ZipArchive();
    $zip_out->open('output.zip', \ZipArchive::CREATE);
    foreach ($files as $file) {
        $zip_out->addFile($file);
    }
    $zip_out->close();
}

Here I am trying to extract input.zip archive to workspace directory to make changes in files contained inside the zip archive. Following this, I want to again zip all the files back into output.zip archive.

The variable $files used to store extracted file names is not touched anywhere while editing the files. The file names are hardcoded and not received via any variable.

The last line to finally save the output.zip archive gives following warning on the console:

PHP Warning: ZipArchive::close(): Read error: Is a directory in /home/user/zip.php on line 100

I am unable to understand the reason for this failure. The error message is unclear. What is the reason for this failure ?

Edit:

As requested, added the code to call the archive handler discussed above.

class A {
    public function A1 () {
        /**
         * the code above
         */
    }
}

class B {
    public function B1 {
        $a = new A();
        $a->A1();
    }
}

This is part of CakePHP 3 app. Taking the hint comments, when I run the code independently outside of CakePHP 3 app it works just fine. However inside the CakePHP app there is some problem. I am adding additional tags to highlight the question in CakePHP community.

i01000001
  • 119
  • 1
  • 2
  • 9

1 Answers1

1

Because your code is wrong and you are replacing the instance of ZipArchive by a file:

$zip = addFile($file);

replace with :

$zip->addFile($file);

Vindic
  • 627
  • 6
  • 8
  • No, it was a typo here on stackoverflow not in actual code. I am making that correction. Thanks for pointing it out ! – i01000001 Feb 09 '17 at 12:58
  • Can you give me the code for $files and be sure that in this files there are only files and not a directory ? – Vindic Feb 09 '17 at 13:04
  • Thanks for taking interest in the question. I have added the required details in the question above. – i01000001 Feb 09 '17 at 15:51
  • Your code is working for me. How do you launch the php script ? – Vindic Feb 10 '17 at 07:48
  • Thanks for the effort in running the code locally. I run the code this way: `class A { public function A1 () { /** * the code above */ } } class B { public function B1 { $a = new A(); $a->A1(); } }` This whole stuff is inside CakePHP 3 app – i01000001 Feb 10 '17 at 12:59
  • Oh! this looks bad I will add it up there – i01000001 Feb 10 '17 at 13:03