Use PHP to zip (archive) a folder

Use PHP to zip (archive) a folder

Here is a very simple way to use PHP to zip up (archive) a folder.

// check for the button to be pressed

if (isset($_POST['archive'])){
	

// Set File name

$filename = "archived.zip";

// Get real path for our folder
$rootPath = realpath('');

// Initialize archive object
$zip = new ZipArchive();
$zip->open($filename, 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();

echo "Archive" .$filename ." was create" ; 

}
else{
	
}

?>

Now just create a button with the name=archive and link the action=”” to your php file ..

Leave a Reply

Be the First to Comment!

Notify of

wpDiscuz