Posted by Duncan on March 9, 2009 – 10:18 pm
I have several web hosting accounts - some are my own, others belong to my clients. I needed to back them up regularly, and I did not want to spend each night for the rest of my life doing manual backups.
My initial thought was to set up an FTP script to do this. However, this would not get any of the mysql databases. What about e-mail account settings, defined sub-domains, and other settings for which I have no record? If I had an account go belly up, I was sunk to remember all of that.
I knew there had to be an easier way to tackle this problem. After a few quick searches, I found a php script that would do a full cpanel backup, and FTP it to the location of your choice. The script can be found here. To set this up, it requires editing the file with your cpanel and FTP credentials, as well as a knowledge of using your cpanel to schedule a cron job (basic instructions for this are in the linked article). Don’t store this file in your public_html folder, as it will contain credentials you don’t want to have compromised.
After discovering this great solution, I ran into another problem: how do I address a growing number of these backups I will have created with ease? I only needed to keep a week of any given site’s backup files. After more searching, I was able to piece together my own script to traverse a directory and delete any files over seven days old (today plus six days):
<?php
//Calls function to traverse the given directory,
//then run the delfile function on any files found
dirtree (”/home/myroot/mybackupfolder”, delfile, array (”date” => date( strtotime(”-6 days”))));
function dirtree ($root, $callback, $params)
{
if (!is_dir ($root.DIRECTORY_SEPARATOR)){
return false; // root directory doesn’t exist
}
$d = dir ($root.DIRECTORY_SEPARATOR);
while (false !== ($entry = $d->read ()))
{
$path = $root.DIRECTORY_SEPARATOR.$entry;
//If it is a folder, recursively call the function again,
//else if a file AND if it ends in file extension gz,
//call the delfile function
if (is_dir ($path) && $entry != “.” && $entry != “..”)
dirtree ($path, $callback, $params);
else if (is_file ($path) && (substr($path , strrpos($path , ‘.’) +1) == “gz”))
$callback ($path, $params);
}
$d->close ();
}
function delfile ($fn, $params)
{
$ft = strtotime (date (”m/d/Y”, filemtime ($fn)));
// delete files on or before the date parameter
if ($ft <= $params['date'])
unlink ($fn);
}
?>
Put this code in a file, modify it to fit your own needs, schedule it with a cron job as well, and you now have a web content backup solution that will maintenance itself.

Duncan,
Thanks so much for sharing this. I will pass it on to Jeff (my administrator).