How to zip a folder and download it using php?

前端 未结 5 2134
伪装坚强ぢ
伪装坚强ぢ 2020-12-15 15:01

I have folder named \"data\". This \"data\" folder contains a file \"filecontent.txt\" and another folder named \"Files\". The \"Files\" folder contains a \"info.txt\" file.

5条回答
  •  天命终不由人
    2020-12-15 15:21

    You need to recursively add files in the directory. Something like this (untested):

    function createZipFromDir($dir, $zip_file) {
        $zip = new ZipArchive;
        if (true !== $zip->open($zip_file, ZIPARCHIVE::CREATE | ZIPARCHIVE::OVERWRITE)) {
            return false;
        }
        zipDir($dir, $zip);
        return $zip;
    }
    
    function zipDir($dir, $zip, $relative_path = DIRECTORY_SEPARATOR) {
        $dir = rtrim($dir, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
        if ($handle = opendir($dir)) {
            while (false !== ($file = readdir($handle))) {
                if (file === '.' || $file === '..') {
                    continue;
                }
                if (is_file($dir . $file)) {
                    $zip->addFile($dir . $file, $file);
                } elseif (is_dir($dir . $file)) {
                    zipDir($dir . $file, $zip, $relative_path . $file);
                }
            }
        }
        closedir($handle);
    }
    

    Then call $zip = createZipFromDir('/tmp/dir', 'files.zip');

    For even more win I'd recommend reading up on the SPL DirectoryIterator here

提交回复
热议问题