Zip Archive a Directory and Download PHP

// ZIPS THIS FOLDER
unlink(__FILE__); //STIL MANUALLY CHECK M'KAY
$rootPath = realpath(__DIR__);
$temp = tmpfile();
$tempPath = $rootPath.'/file.zip'; //stream_get_meta_data($temp)['uri'];
$tempPath = sys_get_temp_dir() . ("/".uniqid().".public_html_dump"); //outside of public_html in tmp

// Initialize archive object
$zip = new ZipArchive();
$zip->open($tempPath, ZipArchive::CREATE | ZipArchive::OVERWRITE);

// Create recursive directory iterator
/** @var SplFileInfo[] $files */
$files = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator($rootPath),
    RecursiveIteratorIterator::LEAVES_ONLY
);

foreach ($files as $name => $file)
{
    // Skip directories (they would be added automatically)
    if (!$file->isDir())
    {
        // Get real and relative path for current file
        $filePath = $file->getRealPath();
        $relativePath = substr($filePath, strlen($rootPath) + 1);

        // Add current file to archive
        $zip->addFile($filePath, $relativePath);
    }
}

// Zip archive will be created only after closing object
$zip->close();

if (file_exists($tempPath)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="'.basename($tempPath).'.zip"');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($tempPath));
    readfile($tempPath);
	unlink($tempPath);
    exit;
} else { 
	
	echo 'error 0x000000001';
	exit;
}


© Jason White 2019 | Privacy Policy | CV | Life Hacks

made with