Php: Automatic Site/Directory Backup via FTP with PHP

Php: Automatic Site/Directory Backup via FTP with PHP
by Janeth Kent Date: 29-04-2013

In this tutorial we are going to make a PHP script that archives your website into a .tar file, then automatically moves it to an external FTP server for safe keeping. We can then setup a cron for this script which will execute it automatically every day/week/month , however frequent you want it. This will only work on Linux servers however that shouldn’t be a problem as most hosts run Linux.

First we’ll setup some variables to allow for easy editing.

$dir = '/path/to/file'; // Directory to backup.
$filename = 'backups/backup' . date("MdY") . '.tar'; //path to where the file will be saved.

$ftp_server = 'urlToFTPServer.Com'; //External FTP server
$ftp_user_name = 'ftpUsername'; //External FTP server username
$ftp_password = 'ftpPassword'; //External FTP server password

Now we need to archive the site. We’re going to wrap an if statement around it so if for some reason it doesn’t archive, the FTP part of the script won’t try and copy it over to another server. The system function executes a system command, here we are calling tar cvf which will archive our $dir (directory) and save it to the path specified in $filename.

if(system("tar cvf $filename $dir")){

We’ll then connect to the FTP server itself. Because we set variables, if we need to change servers, it’s very easy to implement.

$conn_id = ftp_connect($ftp_server);

$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_password);

If it connects to the server, then we can move our backup across. We give it the same name as the archive on our own server and store it in a /backups directory.

if (($conn_id) || ($login_result)) {

$upload = ftp_put($conn_id, 'backups/' . date("MdY") . '.tar', $filename, FTP_BINARY);


Once that is done, we can close the FTP stream as we don’t need to use it anymore.

} //Initial if statement

All thats needed to do is automate this script. For this we use something built into the Linux Operating System called a Cron Tab. Crons will automatically run a script at a time you specify. We can set it up to run every time at the same day so you have a daily backup. You can make this more frequent or less frequent depending on how often the data of your site changes.

by Janeth Kent Date: 29-04-2013 hits : 6281  
Janeth Kent

Janeth Kent

Licenciada en Bellas Artes y programadora por pasión. Cuando tengo un rato retoco fotos, edito vídeos y diseño cosas. El resto del tiempo escribo en MA-NO WEB DESIGN AND DEVELOPMENT.