<?php
// Set the database connection details
$host = 'your_mysql_host';
$user = 'your_mysql_user';
$password = 'your_mysql_password';
$database = 'your_mysql_database';

// Set the path for storing the backup file
$backupPath = '/path/to/backup/directory/';

// Create a unique filename for the backup
$backupFileName = 'backup_' . date('Ymd_His') . '.sql';

// Construct the mysqldump command
$command = "mysqldump -h{$host} -u{$user} -p{$password} {$database} > {$backupPath}{$backupFileName}";

// Execute the command
exec($command, $output, $returnCode);

if ($returnCode === 0) {
    // Output appropriate headers for the download
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="' . $backupFileName . '"');
    header('Content-Length: ' . filesize($backupPath . $backupFileName));

    // Read the backup file and output it to the browser
    readfile($backupPath . $backupFileName);

    // Optionally, you can delete the backup file after downloading
    unlink($backupPath . $backupFileName);
} else {
    echo 'Backup failed. Error code: ' . $returnCode;
}
?>
