open($zipPath, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== true) { deny("Server error: cannot open zip", 500); } $baseLen = strlen($target) + 1; $it = new RecursiveIteratorIterator( new RecursiveDirectoryIterator($target, FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::SELF_FIRST ); foreach ($it as $file) { $fullPath = $file->getPathname(); // Excludes $rel = substr($fullPath, $baseLen); $relNorm = '/' . str_replace(DIRECTORY_SEPARATOR, '/', $rel) . '/'; foreach ($EXCLUDE as $ex) { if (strpos($relNorm, $ex) !== false) { continue 2; } } // Avoid zipping the zipper itself if inside target if (basename($fullPath) === 'mdzip.php') continue; $localName = $dir . '/' . str_replace(DIRECTORY_SEPARATOR, '/', $rel); if ($file->isDir()) { $zip->addEmptyDir($localName); } elseif ($file->isFile()) { // Add file $zip->addFile($fullPath, $localName); } } $zip->close(); // Stream zip to client $downloadName = $dir . '-' . date('Ymd-His') . '.zip'; header('Content-Type: application/zip'); header('Content-Disposition: attachment; filename="' . $downloadName . '"'); header('Content-Length: ' . filesize($zipPath)); header('Cache-Control: no-store'); readfile($zipPath); @unlink($zipPath); exit;