Automatic Local, FTP and Email Backups of MySQL Databases with Cron

I’ll start by saying this is not all my own code, it is based on dagon design’s original release in 2007 (Automatic MySql Backup Script) but this version builds on their version 2.1 to add FTP support.

What this script does:

  • Backup all of your MySQL databases on a server individually, then package them into a single tar.
  • Save that tar locally, on a FTP server or even email it to you

What you need:

  • PHP
  • MySQL
  • An account with relevant mysql access (it needs access to the databases you wish to backup)

Download:

Zip containing dbbackup.php & dbbackupconfig.php – dbbackup.zip

What I’ve added:

To upload to a remote FTP server, I added this to the config file:

######################################################################
## FTP Options
######################################################################

// Use FTP Option?
$useftp = true;

// Use passive mode?
$usepassive = true;

// FTP Server Address
$ftp_server = 'host';

// FTP Username & Password
$ftp_user_name = 'username';
$ftp_user_pass = 'password';

and this to the main file below email sending:

// do we ftp the file?
if ($useftp == true) {
$file = $BACKUP_DEST.'/'.$BACKUP_NAME;
$remote_file = $BACKUP_NAME;

// set up basic connection
$conn_id = ftp_connect($ftp_server);

// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// turn passive mode on?
ftp_pasv($conn_id, $usepassive);

// upload a file
if (ftp_put($conn_id, $remote_file, $file, FTP_BINARY)) {
 echo "successfully uploaded to ftp: $remotefile\n";
} else {
 echo "There was a problem while uploading $remotefile\n";
}

// close the connection
ftp_close($conn_id);
}

That’s all!