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 /.

Archive file is created in the browser accessing arhiva.php. url: http: .. nume_website.tld / wp-content / arhiva.php and at the end of the operation on the file server will be present archive.tar.

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

Stealth

Passionate about everything that means gadgets and IT, I write with pleasure stealthsettings.com from 2006 and I like to discover with you new things about computers and operating systems macOS, Linux, Windows, iOS and Android.

Leave a Comment