Zip and Unzip in PHP

Zip and Unzip in PHP

Code to Zip

open('uploads.zip', 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();
?>

Code to Unzip

open('wordpress-4.1.1-nb_NO.zip') === TRUE) {
    //extract contents to /data/ folder
    $zip->extractTo('/home/3/v/vindu/www/');
    //close the archive
    $zip->close();
    echo 'Archive extracted to data/ folder!';
} else {
    echo 'Failed to open the archive!';
}
?>

Leave a Reply

Your email address will not be published. Required fields are marked *