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:


<?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 occured, details:';
echo $e->getMessage();
}
?>

Careful! The script must be uploaded to the folder where we want to archive the folder and the files that contain them. For example, if we want to archive all the contents of the wp-content folder, al WordPress, the file we named 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.

Passionate about technology, I enjoy writing on StealthSettings.com since 2006. I have a rich experience in operating systems: macOS, Windows, and Linux, as well as in programming languages and blogging platforms (WordPress) and for online stores (WooCommerce, Magento, PrestaShop).

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