Backing up files into a tar.gz and uploading them elsewhere with FTP all in PHP

November 8, 2012

File redundancy is always important. One only learns how important when they lose their site once. If your site is php, you can even create a script to back up your site for you:

$files = "sitefiles_".date('Y-m-d').".tar.gz";
passthru('tar -zcvf  '.$files.' /path/to/files');

The passthru() function is like the exec() function, in that it allows you to run command line commands from a php file. We are using tar.gz to zip our files for maximum compression of size. This can be a big deal for our upload. To upload we use PHP ftp functions.

$server = 'server host here';
$connection = ftp_connect($server);

$login = ftp_login($connection, $ftpuser, $ftpPassword);

if (!$connection || !$login) { die('Connection attempt failed!'); }

$upload = ftp_put($connection, '/path/to/put/files/'.$files, $files, FTP_BINARY);

if (!$upload) { echo 'FTP upload failed!'; }

ftp_close($connection);
passthru('rm '.$files);

This will take the tar.gz file create earlier and upload it to a different server. We add that last command to remove the created tar.gz because we do not need it since it is elsewhere.

Our final script:

$files = "sitefiles_".date('Y-m-d').".tar.gz";
passthru('tar -zcvf  '.$files.' /path/to/files');
$server = 'server host here';
$connection = ftp_connect($server);

$login = ftp_login($connection, $ftpuser, $ftpPassword);

if (!$connection || !$login) { die('Connection attempt failed!'); }

$upload = ftp_put($connection, '/path/to/put/files/'.$files, $files, FTP_BINARY);

if (!$upload) { echo 'FTP upload failed!'; }

ftp_close($connection);
passthru('rm '.$files);

Stay in Touch!

Subscribe to our newsletter.

Solutions Architecture

browse through our blog articles

Blog Archive