Create a Backup Script for the Database that Uploads to AWS
To upload your Database to AWS you need to do the following. This is a PHP Script.
Prerequisites:
1. AWS SDK for PHP: You need to have AWS SDK for PHP installed. You can install it using Composer:
composer require aws/aws-sdk-php
2. AWS Credentials: Ensure your AWS credentials are configured either in the environment or using a credentials file.
<?php
require 'vendor/autoload.php';
use Aws\S3\S3Client;
use Aws\Exception\AwsException;
// Database credentials
$dbHost = 'your_db_host';
$dbUser = 'your_db_user';
$dbPass = 'your_db_password';
$dbName = 'your_db_name';
// AWS S3 credentials and bucket name
$bucketName = 'your_bucket_name';
$region = 'your_region';
$s3Client = new S3Client([
'version' => 'latest',
'region' => $region,
]);
// Backup file path
$backupFile = '/path/to/backup_' . date('Y-m-d_H-i-s') . '.sql.gz';
// Create the backup
$command = "mysqldump --opt -h $dbHost -u $dbUser -p$dbPass $dbName | gzip > $backupFile";
system($command, $output);
if ($output === 0) {
echo "Database backup successfully created.\n";
try {
// Upload the backup to S3
$result = $s3Client->putObject([
'Bucket' => $bucketName,
'Key' => basename($backupFile),
'SourceFile' => $backupFile,
]);
echo "Backup uploaded to S3: " . $result['ObjectURL'] . "\n";
// List objects in the bucket to find old backups
$objects = $s3Client->listObjectsV2([
'Bucket' => $bucketName,
]);
// If more than 1 backup exists, delete the oldest one
if (isset($objects['Contents']) && count($objects['Contents']) > 1) {
// Sort objects by LastModified date
usort($objects['Contents'], function ($a, $b) {
return strtotime($a['LastModified']) - strtotime($b['LastModified']);
});
// Delete the oldest object
$oldestObject = $objects['Contents'][0];
$s3Client->deleteObject([
'Bucket' => $bucketName,
'Key' => $oldestObject['Key'],
]);
echo "Old backup deleted: " . $oldestObject['Key'] . "\n";
}
} catch (AwsException $e) {
echo "Error uploading backup to S3: " . $e->getMessage() . "\n";
}
// Remove the local backup file
unlink($backupFile);
} else {
echo "Failed to create database backup.\n";
}
?>
Steps to Use the Script:
1. Replace your_db_host, your_db_user, your_db_password, your_db_name, your_bucket_name, and your_region with your actual database and AWS S3 details.
2. Set the $backupFile path to where you want to temporarily store the backup file before uploading it to S3.
3. Run the script using PHP from the command line or set it up as a cron job for periodic backups.
How It Works:
• The script creates a gzipped MySQL database dump using mysqldump.
• The backup is then uploaded to an S3 bucket.
• After uploading, the script checks if there are multiple backups in the S3 bucket and deletes the oldest one, ensuring only one backup is retained.
• Finally, the local backup file is deleted to save disk space.
This script will ensure that only one backup is retained in your S3 bucket, keeping your storage tidy and manageable.