Create daily backup for your website and mysql in Cpanel

I have a good friend in Australia who bought a hosting package from godaddy (I don’t know if it’s a good deal) with no backup service attached. Many times you work and break the code so it is important to have a backup for your site and for mysql .

1. Create daily backup for mysql database

Create a file backup-mysql.sh and backup folder into the public_html directory and add in the file the bellow code. Replace database credentials and your_account_name with yours.

#!/bin/bash

# Database credentials
 user="your-database-username"
 password="your-database-password"
 host="localhost"
 db_name="your-database-name"

# Other options
 backup_path="/home/your_account_name/public_html/backup/mysql"
 date=$(date +"%d-%b-%Y")

# Set default file permissions
 umask 177

# Dump database into SQL file
 mysqldump --user=$user --password=$password --host=$host $db_name > $backup_path/$db_name-$date.sql

# Delete files older than 30 days
 find $backup_path/* -mtime +30 -exec rm {} \;

 

2. Create daily backup for your site

Create a file backup-daily.sh into the public_html directory and add the bellow code. Replace your_account_name and example.com

#!/bin/bash
if [ -s /home/your_account_name/public_html/backup/example.com-daily.tar.gz ]
then
    rm /home/your_account_name/public_html/backup/example.com-daily.tar.gz
fi
tar -czf /home/your_account_name/public_html/backup/example.com-daily.tar.gz /home/your_account_name/public_html/example.com

 

Now all you have to do is go to Cpanel / Cronjobs and add two cronjobs to run daily (replace your_account_name)

sh /home/your_account_name/public_html/backup-daily.sh >/dev/null 2>&1

sh /home/your_account_name/public_html/backup-mysql.sh >/dev/null 2>&1

You can also create weekly (monthly) backups in the same way. Just create another file replace daily with weekly and set the cronjob to run every week.

Good luck!

 

Leave a Reply

Your email address will not be published. Required fields are marked *