ohctech_p8/auto_backup_db.php
2024-10-16 19:18:52 +05:30

64 lines
1.4 KiB
PHP

<?php
// Database configuration
$host_name = "localhost";
$database_name = "volvo";
$database_user = "root";
$database_password = "";
$backupDir = 'database/backup/';
// Ensure the backup directory exists
if (!file_exists($backupDir)) {
mkdir($backupDir, 0755, true);
}
// Date format for backup filename
$date = date('Y-m-d_H-i-s');
// Backup file name
$backupFile = $backupDir . $database_name . '_' . $date . '.sql';
// Command to execute the backup
$command = sprintf(
'mysqldump --opt -h %s -u %s -p%s %s > %s',
$host_name,
$database_user,
$database_password,
$database_name,
$backupFile
);
// Execute the command and check if it was successful
$output = array();
$result = 0;
exec($command, $output, $result);
if ($result !== 0) {
die('Backup failed: ' . implode("\n", $output));
} else {
echo "Backup completed successfully.\n";
}
// Function to delete old backups
function deleteOldBackups($dir, $days = 5) {
$files = glob($dir . '*.sql'); // Get all backup files
$now = time();
foreach ($files as $file) {
if (is_file($file) && $now - filemtime($file) >= 60 * 60 * 24 * $days) {
if (unlink($file)) {
echo "Deleted old backup: $file\n";
} else {
error_log("Failed to delete old backup: $file");
}
}
}
}
// Delete backups older than 3 days
deleteOldBackups($backupDir);
echo "Old backups deleted successfully.\n";