* @link https://wiki.helmutkaczmarek.de/code:php:backup:mysql */ header('Content-Type: text/html; charset=utf-8'); // MySQL connection data $host = 'localhost'; $user = 'username'; $password = 'passwort'; $database = 'databasename'; $dumpname = 'hourly'; // For visual distinction if, for example, "hourly", "daily" and "weekly" backups are stored in the same folder. // Directory for the backups (if not present, then create) $backupDirectory = '/www/htdocs/vXXXXXX/path/to/folder/'; if (!is_dir($backupDirectory)) { mkdir($backupDirectory, 0777, true); } // Number of backups to keep $maxBackups = 3; // Create backup file $backupFile = $backupDirectory . $dumpname . '_' . $database . '_' . date('Y-m-d_H-i-s') . '.sql.gz'; // Backup and zip database $command = "mysqldump -h {$host} -u {$user} -p{$password} {$database} | gzip > {$backupFile}"; exec($command, $output, $returnVar); if ($returnVar === 0) { echo "Database backed up successfully: {$backupFile}"; // Get a list of existing backups $backupFiles = glob($backupDirectory . $dumpname . '_' . $database . '_*.sql.gz'); if (count($backupFiles) > $maxBackups) { // Sort backups by date (oldest first) usort($backupFiles, function ($a, $b) { return filemtime($a) > filemtime($b); }); // Delete older backups $filesToDelete = array_slice($backupFiles, 0, count($backupFiles) - $maxBackups); foreach ($filesToDelete as $file) { echo "
Deleted: " . $file; unlink($file); } } } else { echo "Error saving database: " . $output; } ?>