views:

66

answers:

2

I'm creating an SQL file, placing this file into a zip file with some images and then deleting the SQL file with unlink.Strange thing is it deletes the zip file as well.

if (file_put_contents($sqlFileName, $sql) !== false) {
        $zip = new ZipArchive;
        if ($zip->open($workingDir . $now . '.zip', ZipArchive::CREATE) === true) {
            $zip->addFile($sqlFileName, basename($sqlFileName));
            if(! empty($images)) {
                foreach ($images as $image) {
                    $zip->addFile($imagesDir . $image, $image);
                }
            }
        }
        unlink($sqlFileName);
}
+1  A: 

unlink() never deletes more than one file. Your zip file isn't created in the first place, because you don't close the archive - which basically tells PHP to wrap up the archive's headers, do the compression, etc. Append $zip->close() to your code.

UPDATE I just read that ZipArchive::close() is called automatically at the end of the script, so this leaves just two options: Either your call to zip->open() fails. or your code isn't entering the foreach loop - leaving you with an empty archive. Empty archives do not get created according to a comment in the function's doc.

soulmerge
+1 for doing research on ZipArchive.
Pekka
Although zip close is called at the end of the script automatically, because I'm deleting a resource before I close the zip, the zip doesn't get created
RMcLeod
+2  A: 

As written in http://www.php.net/manual/en/function.ziparchive-addfromstring.php:

jared at kippage dot com 03-Sep-2009 01:08

It may seem a little obvious to some but it was an oversight on my behalf.

If you are adding files to the zip file that you want to be deleted make sure you delete AFTER you call the close() function.

If the files added to the object aren't available at save time the zip file will not be created.

The simple solution: Add $zip->close() before you call unlink($sqlFileName); and you should be fine.

Cassy
+1 that makes sense.
zaf