Search code examples
phpfilesystemsphp-ziparchive

ZipArchive::close() returns false even with all permissions in folder


Everything works fine on localhost, but when I try to get this script to work on server I couldn't. I tried to change permission of root and uploads (where uploaded images are and where .zip files should be created) to 777 (I know it's not safe, but I just tried to test because it worked on localhost) but it doesn't. I also don't get any additional errors, and error reporintg (E_ALL) is turned on in php.ini. Directories are also created normally in that folder via mkdir() function.

Here is the function for zipping folders:

function Zip($source, $destination)
{

    if (!extension_loaded('zip') || !file_exists($source)) {
        return false;
    }

    $zip = new ZipArchive();
    if (!$zip->open($destination, ZIPARCHIVE::CREATE)) {
        return false;
    }

    $source = str_replace('\\', '/', realpath($source));

    if (is_dir($source) === true)
    {
        $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);

        foreach ($files as $file)
        {
            $file = str_replace('\\', '/', $file);

            // Ignore "." and ".." folders
            if( in_array(substr($file, strrpos($file, '/')+1), array('.', '..')) )
                continue;

            $file = realpath($file);

            if (is_dir($file) === true)
            {
                $zip->addEmptyDir(str_replace($source . '/', '', $file . '/'));
            }
            else if (is_file($file) === true)
            {
                $zip->addFromString(str_replace($source . '/', '', $file), file_get_contents($file));
            }
        }
    }
    else if (is_file($source) === true)
    {
        $zip->addFromString(basename($source), file_get_contents($source));
    }

    return $zip->close();
}

if (Zip($folder.$archiveName."/", $folder.$archiveName.".zip")) {
    echo "Done.";
    rrmdir($folder.$archiveName."/");
} else {
    addError("Error while trying to compress files.");
}

I also tried to write out the error message:

if ($zip->close()) {
    echo "Done.";
}
else {
    echo $zip->getStatusString();
}

But it doesn't write out anything.


Solution

  • Problem is solved - I localized problem with debugging and realized that zip extension wasn't loaded. In case you encounter this problem too (site is deployed on DigitalOcean) and you're using Debian or derivative just install php7.0-zip package:

    sudo apt-get install php7.0-zip