How to Compress Files on the Server Using PHP

Posted in Tutorials

Tweet This Share on Facebook Bookmark on Delicious Digg this Submit to Reddit

Have you ever have to download a bunch of files from the server onto your local computer?  Even with an FTP client, it takes a while when you got a lot of files (such as when backing up a whole set of WordPress files).

If you have access to the webhost with a cPanel File Manager that lets you select all the files and compress them into a tarball (files tarred and then gzipped), then it will download faster as a single compressed file.

But what if you only have FTP access?  In this tutorials, we will write a simple PHP script that would do something similar.  You upload that script to the server.  Run the PHP script from your browser.   And it produces a tarball file which you can then download.  Remember to delete that script afterwards.  And delete the tarball after downloading if you don’t need it.

1.  Create a file called “compress-files.php” with the following contents …

exec('tar zcf thecompressedfiles.tar.gz *');

2. Upload this file to your server in the folder that contains the files you want to compress.

3. Navigate to the compress-files.php file in your browser.  Once you load that PHP file in your browser it will run that command.  That command will tar and gzip everything in that folder (except for files that starts with dot) to produce the file thecompressedfiles.tar.gz. You may need to refresh your FTP client to see the newly produced file.

4.  Now you can download the gz file, which you can then compress using 7-zip (or similar utility).  After un-compressing, you get a tar file.  Then use 7-zip and extract it to get your individual files.

5. Delete the compress-file.php PHP script file from your server.  And delete the gz file too if you don’t need it.


The exec command allow the PHP script to execute an external program.

In this case, we ask it to run the Linux/Unix tar command to create the tarball file.  The flags z, c, and f indicates to zip, create, file.   More info on the command.

Does Not Work When …

Filenames that starts with a dot (such as in .htaccess) are not included in the compressed file. You have to download these individually yourself. This is because the wildcard * does not capture the files that starts with dot.

Also will not work if exec has been disabled in PHP.