/ Published in: PHP
This handy little script will backup your website's database (MySQL) and files and put them into an amazon s3 bucket.
Expand |
Embed | Plain Text
<?php //to use this script //1) Download S3.php from http://undesigned.org.za/2007/10/22/amazon-s3-php-class //2) Place the S3.php file in the same folder as this script //3) Adjust these variables accordingly $access_key = ''; $secret_key = ''; $bucket = 'backups'; $site_name = 'mysite'; $site_directory = "/path/to/public_html"; $db_host= "localhost"; $db_user = ""; $db_pass= ""; $db_name= ""; $mail_on_error = TRUE; $mail_to = ""; //4)call this script with curl or wget in a cron task //curl --silent --compressed http://example.com/s3_backup.php?key=trc_2011 //-or- //wget -O - -q -t 1 http://www.example.com/s3_backup.php?key=trc_2011 //little bit o' security so script cannot be misused if($_GET['key'] == 'trc_2011'){ require 'S3.php'; try{ $s3 = new S3($access_key, $secret_key); $s3->putBucket($bucket, S3::ACL_PRIVATE); //get current dir //create database dump echo "Creating database backup...<br/>"; $db_backup_file = $cwd.'/'.$site_name.'.sql'; exec("mysqldump --add-drop-table --user=$db_user --password=$db_pass --host=$db_host $db_name > $db_backup_file"); //store it echo "Uploading database backup...<br/>"; $s3->putObjectFile($db_backup_file, $bucket, $site_name.'/'.$site_name.'.sql', S3::ACL_PRIVATE); //delete it //create filesystem backup echo "Creating filesystem backup...<br/>"; $fs_backup_file = $cwd.'/'.$site_name.'.tgz'; //change to site directory so .tgz will have correct paths when extracted //create backup //change back to original directory //store it echo "Uploading filesystem backup...<br/>"; $s3->putObjectFile($fs_backup_file, $bucket, $site_name.'/'.$site_name.'.tgz', S3::ACL_PRIVATE); //delete it echo "Backup Complete"; } catch(Exception $e){ if($mail_on_error){ $subject = "Site Backup Script Error - ".$site_name; $body = "S3 Site Backup Script Failed : ".$e->getMessage(); } } } ?>
Comments
Subscribe to comments
You need to login to post a comment.

Great little snippet. If I could suggest a couple of improvements:
1) It would probably be wise to compress your SQL dump file, as it'll compress incredibly well (the tar file of your filesystem could probably benefit from compression too). This could save you quite a bit of money with Amazon in the long run! 2) Encrypt your backups, as they might contain sensitive information (such as database passwords etc.). Even specifying a 7zip/zip password would work.
And finally, if you want a free way to back up your website and database to S3, you could use my service where I've done it all for you! http://www.backupmachine.com/