WordPress backup


I want to do an automatic weekly backup of the blogs hosted on my server. The scripts I found require you to specify the database name, the user name and the password in the script. However this is not an option because I want to do the backups without modifying the script when I add or delete a blog.

The default wp-config.php in Debian searches for a configuration file based on the blog’s host, so you can host more than one blog on the same system. These cofiguration files have the following format:

<?php
define('DB_NAME', 'xxx');
define('DB_USER', 'xxx');
define('DB_PASSWORD', 'xxx');
define('DB_HOST', 'localhost');

$table_prefix  = 'wp_';

$server = DB_HOST;
$loginsql = DB_USER;
$passsql = DB_PASSWORD;
$base = DB_NAME;
?>

My script extracts the needed parameters from the configuration files and dump the database to a gzipped backup file.

#! /bin/sh

# Backup directory
dir=wp-backup-`LC_ALL=C date +%d%b%y-%H.%M`

mkdir $dir

# Set the variable in $2 to the value read from the
# config-*.php file passed in $1.
function getval() {
    eval $2=`grep "'$2'" < $1 | \
        sed -e "s/define('$2', '\([^']*\)');/\\1/"`
}

for f in /etc/wordpress/config-*.php; do
    # Skip symbolic links, I use them to have a
    # blog accessible from different addresses,
    # such as localhost and 127.0.0.1.
    if [ ! -L $f ]; then
        getval $f DB_NAME
        getval $f DB_USER
        getval $f DB_PASSWORD
        bak_file=`basename $f | sed -e \
            's/config-\(.*\)\.php$/\\1/'`.sql.gz
        # Dump the database $DB_NAME and compress
        # it. The --skip-opt option is needed on
        # my system, maybe you can omit it.
        mysqldump --skip-opt --add-drop-table \
            --allow-keywords -q -a -c -u $DB_USER \
            -p$DB_PASSWORD $DB_NAME | \
            gzip --best > $dir/$bak_file
    fi
done

Note that the script saves every table in the database. If you have any statistics or anti-spam plugins they could generate some big tables you may want to skip. To do this pass to mysqldump, after the database name, the tables you want to save. AFAIK for WordPress 2 these are: wp_categories, wp_comments, wp_linkcategories, wp_links, wp_options, wp_post2cat, wp_postmeta, wp_posts, wp_usermeta, wp_users.

Information and Links

Join the fray by commenting, tracking what others have to say, or linking to it from your blog.


Other Posts

Reader Comments

Sorry, comments are closed.