Automate MySQL Database Backup to Amazon AWS S3 (using PHP)

Published On: 18 August 2015.By .
  • Digital Engineering

Databases.

A database is an organized collection of data. It is the collection of schemas, tables, queries, reports, views and other objects. The data is typically organized to model aspects of reality in a way that supports processes requiring information, such as modelling the availability of rooms in hotels in a way that supports finding a hotel with vacancies. – Wikipedia

Generally, databases are frequently updated. Dynamic nature of databases makes it inefficient to take manual backups regularly. Sure you can create a mysqldump on the server itself with a simple script, but what if the server crashes?

To deal with this issue, you can create a backup of database and upload it to a remote (and reliable) server regularly – using script. We’ll use AWS S3 for this tutorial as it’s reliable and easy to set up. Let’s start with the backup function first.

There. Database backup file is generated and saved in the specified directory on the server itself. Do note that filename is prefixed with current timestamp using PHP time() function. We’ll use this timestamp to delete backup files older than a certain time period. Now we just need to move the file to AWS S3 server.

Get AWS SDK

Download AWS SDK for PHP from Amazon and include it in your project: http://docs.aws.amazon.com/aws-sdk-php/v3/guide/getting-started/installation.html

The PHP Class

Here’s a small piece of code, and that’s all you need to get the script up and running. Make modifications as per your requirements.

This class is used for:

  • Check if the file you’re trying to upload is valid and not too large.
  • Check if AWS Bucket exists, if not then create one. Buckets on AWS S3 are like directories.
  • Get all files list in the bucket, use timestamp prefix to delete files older than specified limit. This is important to keep total size of backups on S3 in control.
  • And of course, upload the file to AWS S3 using multipart.

You can also create a function to delete local backup file after upload is completed successfully.

Instantiate UploadToAWS

That’s it. All there’s left to do is create a cron job to schedule the task at regular intervals and sleep peacefully. If you have any questions, shoot them in comments section below.

Related content

That’s all for this blog