How to create a. Tard and director (folders) archive on the server, using a PHP script

A very simple solution in many situations, for a quite serious problem. In the scenario in which we would have to move a website, whose files number several thousand, and the web hosting provider does not ensure a Sistem de Backup with archive or other similar method to allow us, transfer through FTP It is a solution that would take a lot of time.

A PHP script climbed on the server that hosts the website would help us to do Archivation in .tar format of all files in a folder.

How do we archive files and folders on a web server, using in the PHP script?

We copy the script below and put it in a .php file on the server. Example: Archive.php SA contains 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 climbed into the folder in which we want to archive the folder and files that contain them. For example, if we want to archive all the contents of the WP-Content Folder, of WordPress, the file called by us the archive.php will be climbed in /wp-account /.

The archive is created by accessing the archive.php file in the browser. URL: http: .. name_website.tld/wp-account/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 value of “timeout” of the execution time. You can do this from PHP.ini or .htaccess.

Passionate about technology, I write with pleasure on stealthsetts.com starting with 2006. I have a rich experience in operating systems: Macos, Windows and Linux, but also in programming languages ​​and blogging platforms (WordPress) and for online stores (WooCommerce, Magento, Presashop).

Home Your source of IT tutorials, useful tips and news. How to create a. Tard and director (folders) archive on the server, using a PHP script
Leave a Comment