Here is a script that will allow you to backup your database whenever you want to. Just set a Cron Job to point to this script and you are golden!!! Be sure to change the variables to your values before trying to run this.
// database back up with email notification // Use Crontab to automate // make file executable // Define your parameters, // Best defined in a include file for security purposes $host = "localhost"; $username = "root"; $password = "password"; $dbname = "database_name" // define the file name $backup = $dbname.date("Y-m-d_H:i:s").'.gz'; // define the path to the file // we puposely do this outside the web directory $path = "/home/username/backups/"; // combine into one string $backup_file = $path.$backup; // for email $email = "myemail@domain.com"; $subject = "MySQL Dump Completed succesfully"; $body = "You MySQL back up for $backup is available at:\n\n $backup_file\n\n" $body.= "thank you,\n Your friendly Linux Box!"; // the mysql command $command = "mysqldump --opt -h $host -u $username -p $password $dbname | gzip > $backup_file"; // Now that all that is defined lets run the script if(exec($command)){ // run the command if(file_exists($backup_file)){ mail($email, $subject, $body); } else { // redefine some variables for mail $subject = "MySQL Dump Failed miserably"; $body = "You MySQL back up for $backup Failed:\n\n $backup_file\n\n" $body.= "So Sorry,\n Your friendly Linux Box!"; mail($email, $subject, $body); } } else { $subject = "Failed to execute command"; $body = "You MySQL back up for $backup Failed to execute:\n\n $command\n\n" $body.= "So Sorry,\n Your friendly Linux Box!"; mail($email, $subject, $body); }
Here is what you put into your crontab file: we assume you are running this file from outside your web directory (public_html, htdocs) in a folder called backups that you have already created. This runs the script at 1am every sunday
0 1 * * 0 usr/bin/php /home/username/backups/database_backup.php >/dev/null 2>&1
Remember you must have permission to write Cron Jobs on your server. Also, The PHP file must be chmod 755.