<?php /** * mysql_backup.php * * Creates backup files of all databases on specified MySQL hosts * @author Chad Kieffer, ckieffer@gmail.com * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * To obtain a copy of the GNU General Public License, write to the Free * Software Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA * 02110-1301, USA. */ // DB connection and server settings $dbuser = 'user'; $dbpass = 'passwd'; $dbservers = array( 'host1.com', 'host2.com', 'host3.com' ); $mysqldump = '/usr/local/mysql/bin/mysqldump'; $logfile = dirname(__FILE__) . '/mysql_backup.log'; $to = 'you@yourdomain.com'; $subject = 'MySQL Dump Report'; foreach ($dbservers as $k => $dbhost) { // Initialize/reset log message variable and backup path $message = ''; $directory = dirname(__FILE__) . "/$dbhost"; // If archive directory doesn't exist for the dbhost, make one if (!is_dir($directory)) { mkdir($directory, 0755); } // If an archive directory exists, backup the db if (is_dir($directory)) { // The dump archive to save $archive = "$directory/$dbhost" . date("Ymd-Hi") . '.sql.gz'; // The mysqldump command for this archive, 2>&1 captures error output $command = "$mysqldump --all-databases --opt --quick -h $dbhost " . "-u $dbuser -p$dbpass 2>&1 | gzip > $archive"; // Execute the command $output = shell_exec($command); // Write to the log file if (preg_match('/Got error/', $output)) { $message .= date(YmdHis) . " - $output\n"; } else { $message .= date(YmdHis) . " - Successfully dumped and saved $archive\n"; } } else { $message .= date(YmdHis) . " - ERROR: $directory does not exist, " . "mysqldump aborted\n"; } // Append messages to log $fh = fopen($logfile, 'a') or die("Unable to open $logfile"); fwrite($fh, $message); fclose($fh); // Add to an email message $email .= $message; } // Send session output to the DBA mail($to, $subject, $email); ?>