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 PHP script?

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

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 occured, 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 file arhiva.php in the browser. url: http: ..web_name.tld / wp-content / archive.php, and at the end of the operation on the server will be present the archive.tar file.

If you have a large volume 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 gadget and IT, I write with pleasure on since 2006 and I like to discover with you new things about computers and operating systems macOS, Linux, Windows, iOS and Android.

Leave a Comment