MySQL Hot Backup with PHP
I often Google for code that I want to use, but I don't often find exactly what I want. Usually what I find is too far and beyond what I actually want--something simple. Othertimes it's written in Perl, which I'm sorry but I just have no desire to really master even though it's not that hard. I really want to just do it in PHP so that I can alter it.
Well tonight I just created a simple PHP script to backup my database and then tarball and gzip it. Next time I will add some more in there to upload it to Amazon S3 and email me the report. But without further ado, here is the code...
$mysql_user = 'root';
$mysql_pass = '......';
$mysql_db = '......';
$backup_path = '/second_drive/backups/mysql/';
$twodaysago = date('Ymd', strtotime('-2 days'));
$yesterday = date('Ymd', strtotime('-1 day'));
$today = date('Ymd');
// Remove backup from two days ago
if (file_exists("$backup_path/$yesterday")) {
if (file_exists("$backup_path/$twodaysago")) {
echo "Deleting backup from two days ago...n";
unlink("$backup_path/$twodaysago/$mysql_db.tar.gz");
rmdir("$backup_path/$twodaysago");
}
}
// Create today's folder
echo "Creating today's folder...n";
mkdir("$backup_path/$today");
// Making today's backup
echo "Creating hot copy...n";
$cmd = "mysqlhotcopy --user=$mysql_user --password=$mysql_pass $mysql_db $backup_path/$today/";
system($cmd);
// Tar today's backup
echo "Creating tarball...n";
$cmd = "tar -cvf $backup_path/$today/backup.tar $backup_path/$today/*";
system($cmd);
// Gzip today's backup
echo "Gzipping it up...n";
$cmd = "gzip $backup_path/$today/backup.tar";
system($cmd);
// Send to Amazon
// ...
// Done
echo "Done.n";
?>
UPDATE: This script was updated here.
Comments