How to create a tar archive of files and directories (folders) on the server using a PHP script

A very simple solving in many situations, for a pretty serious problem. In the scenario where we have to move a website, whose files number a few thousand, and the web hosting provider does not provide us with a backup system with archiving or other similar method that allows us this, FTP transfer is a solution that we would take a very long time.

A PHP script uploaded to the server that hosts the website would help us do it tar format archiving of all files in a folder.

How do I archive files and folders on a web server using the PHP script?

Copy the script below and put it in a .php file on the server. Example: arhiva.php contain the script below:

[php] <? php
try {
// make sure the script has enough time to run (300 seconds = 5 minutes)
ini_set ('max_execution_time', '300');
ini_set ('set_time_limit', '0');
$target = isset ($ _ GET ["targetname "])? $ _GET ["targetname "]: 'archive.tar'; // default to archive.tar
$ dir = isset ($ _GET ["dir"])? $ _GET ["dir"]: './.'; // defaults to all in current dir
// setup phar
$ phar = new PharData ($target);
$ Phar-> buildFromDirectory (dirname (__FILE__). '/'.$dir);
echo 'Compressing all files done, check your server for the file '. $target;
} catch (Exception $ e) {
// handle errors
echo 'An error has occurred, details:';
echo $ e> getMessage ();

[/ Php]

Careful! Script must be uploaded to the folder where we want to archive the folder and the files it contains. For example, if we want to archive all the contents of the wp-content folder, WordPress, the file named by us arhiva.php will be uploaded to / wp-content /.

The archive is created by accessing the archive.php file in the browser. url: http: / wp-content / archive.php, and the archive.tar file will be present at the end of the server operation.

If you have a large amount of files, change the timeout value of the execution time. You can do this from php.ini or .htaccess.

How to create a tar archive of files and directories (folders) on the server using a PHP script

About the author


Passionate about everything that means gadget and IT, I am pleased to write on from 2006 and I love to discover new things about computers and macOS, Linux operating systems, Windows, iOS and Android.

Leave a Comment