Zip and Unzip with PHP Script

Having trouble uploading/downloading large number of files through ftp where archive and extract options are not available? Wasting your developing and testing time waiting? There are lots of hosting providers whose control panel doesn’t supports archiving and extraction from their control panel. Thus when uploading/downloading website files which are in number of thousands takes hours to complete. Are you going to wait around that time or simply think ahead and use some scripts to archive files to download and extract uploading archived file.

We will be using ZipArchive class . ZipArchive archives files to .zip extension and extracts .zip extension archive files.

ZipArchive class needs Zip extension enabled on a server to work. Before executing the code let’s check if your server has Zip extension enabled or not.

There are lots of way to verify it but we are using the easiest ways.

Check phpinfo

create a php file with a name (i prefer the file name info.php) containg following script :

<?php
phpinfo();
?>

Upload it to your web folder. I recommend to upload it on your root directory. Execute the php script by visiting the file you just created.

For example, if you uploaded file info.php to root directory of domain ‘yoursite.com’ then browse your file from ‘yoursite.com/info.php’ . Check the zip section php information. If your server has Zip extension installed and enabled it will show the information.

Upload the php file you created to the directory you want to archive. Run the file from the link address and wait until it finishes archiving the files and it will show Files has been archived after finishing archiving. Now you can download the zip file instead of downloading all the files one by one.

If you want to archive the yoursite.com/wp-content/ directory upload it to /wp-content/ directory and run it from yoursite.com/wp-content/zip.php

If your directory contains very large number of files it will take more time to archive all the files and it is depended to maximum execution time defined on php value . If you have very large number of files and have only set 30 seconds of time limit the archiving process might end with out archiving whole files or not creating archived file. So consider the php maximum execution time limit as well.

For extracting the zip file you can use following simple php script. Create a php file with following script and replace the file.zip with the name of your zip file needed to be extracted to the directory and change the /my/destination/dir/ to the directory path you need the files to be extracted.