Create extract zip files using php
Uploading and downloading files to and from web servers is a common task in web development environment.
This task is simple and straight forward as long as we have to process few files or have cPanel access, in which case we can upload the archived files and extract them on server.
However, when we have to upload a bulk of files to a webserver or we have to download a large number of files from the server, and we have only ftp access, this can sometimes turn into a nightmare.
For such situations, we can use php to extract a zip archive on the server as well as create an archieve on the server.
Create extract zip files using php
To create a zip file in php we will make sure that all the archive is created recursively and all the sub-folders are also included. To accomplish this in easy way, we will use RecursiveDirectoryIterator
Php script to create zip archive
//specify the folder that you want to archive define('SOURCE', 'path/to/our/source/folder'); // add timestamp to the target file name to prevent accidental overwrite Zip(dirname(__FILE__) . '/'. SOURCE, dirname(__FILE__).'/'.SOURCE.'-'.time().'.zip'); function Zip($source, $destination) { if (!extension_loaded('zip') || !file_exists($source)) { //check if php zip extension is present return false; } $zip = new ZipArchive(); if (!$zip->open($destination, ZIPARCHIVE::CREATE)) { return false; } $source = str_replace('\\', '/', realpath($source)); if (is_dir($source) === true) { //use RecursiveDirectoryIterator to loop through nested subfolders $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST); foreach ($files as $file) { $file = str_replace('\\', '/', $file); // Ignore "." and ".." folders if( in_array(substr($file, strrpos($file, '/')+1), array('.', '..')) ) continue; $file = realpath($file); if (is_dir($file) === true) { $zip->addEmptyDir(str_replace($source . '/', '', $file . '/')); } else if (is_file($file) === true) { $zip->addFromString(str_replace($source . '/', '', $file), file_get_contents($file)); } } } else if (is_file($source) === true) { $zip->addFromString(basename($source), file_get_contents($source)); } return $zip->close(); }
This will create a zip archive of the specified source folder.
Next we will see how can we extract a zip archive using php
PHP script to extract zip archive.
$zip = new ZipArchive; if ($zip->open('/path/to/archive.zip') === TRUE) { $zip->extractTo(__DIR__); $zip->close(); echo 'Archive extracted in '.__DIR__; } else { echo 'Extraction failed'; }