How to auto backup the wordpress site

Backup is important when you run a website. For me I backup this blog which is powered by wordpress automatically, once the blog’s content gets updated.

This is the perl script to run in crontab, which checks the database to see if there is any update, if yes a backup will be implemented.

#!/usr/bin/perl
 use strict;
 use MySQL::mycrud;
  
 my $db = MySQL::mycrud_>new('my_user','127.0.0.1',3306,'my_database','my_passwd');
 my ($last_id) = $db->get_row("select ID from wp_posts order by ID desc limit 1");
 $db->disconnect;
 
 open HD,"/tmp/last-id.txt" or die $!;
 my $record_id = <HD>;
 close HD;

 chomp $record_id;

 if ($last_id > $record_id) {
     system "/path/to/backup.sh";  # implement a bash script
     open HDW,">","/tmp/last-id.txt" or die $!;
     print HDW $last_id;
     close HDW;
 }  

And, this is the bash script called by perl above, which implements the full backup for a wordpress site, including the site files and database.

#!/bin/bash

 cd /tmp
 DATE=`date +%Y-%m-%d`
 DIR="mysite.$DATE"

 mkdir -p $DIR
 
 # copy the site files from webdir
 sudo cp -rf /var/www/mysite/ $DIR/

 # dump database
 sudo mysqldump -uroot my_database > $DIR/my_database.sql
 sudo chown -R your_user_id $DIR
 
 tar zcf $DIR.tgz $DIR/
 rm -rf $DIR
 
 rclone copy $DIR.tgz dropbox:webbackup 

You should change the script to mach your use case, such as dir name, database name, user ID etc. And I upload the backup file to dropbox via rclone, you maybe want to change it with another way.

Print Friendly, PDF & Email