Zip and Unzip in PHP
- سُلَيْمَان بْن دَاوُوْد

- Jun 21, 2020
- 1 min read
Code to Zip
<?php //echo getcwd(); die;$rootPath = realpath('/home/cififacywac8/public_html');// Initialize archive object$zip = new ZipArchive();$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
<?php $file = "wordpress-4.1.1-nb_NO.zip";$zip = new ZipArchive;//open the archiveif ($zip->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!';}?>
Comments