Skip to content

Instantly share code, notes, and snippets.

@waffle2k
Created December 11, 2013 19:38
Show Gist options
  • Save waffle2k/7916962 to your computer and use it in GitHub Desktop.
Save waffle2k/7916962 to your computer and use it in GitHub Desktop.
A simple little script that backs up the wordpress/mysql database. It requires a ~/.wpbackup file with at least the line "SOURCE_FROM_WP" and "WPLOC=/location/of/wordpress" in it.
#!/usr/bin/perl
use strict;
sub extract_from_config {
my $filename = shift || die;
my $variable = shift || die;
open my $fd, "<$filename" or die "$filename: $!";
while( <$fd> ){
chomp;
if( /define\s*\(\s*\'$variable\'\s*,\s*\'(\S+?)\'/ ){
return $1;
}
}
return undef;
}
my ( $WPUN, $WPPW, $WPDB, $WPHN, $WPLOC, $SOURCE_FROM_WP );
if( -e "$ENV{HOME}/.wpbackup" ){
open my $fd, "<$ENV{HOME}/.wpbackup";
while( <$fd> ){
chomp;
$WPUN = $1 if /^WPUN=(\S+)/;
$WPDB = $1 if /^WPDB=(\S+)/;
$WPHN = $1 if /^WPHN=(\S+)/;
$WPLOC= $1 if /^WPLOC=(\S+)/;
$SOURCE_FROM_WP = 1 if /^SOURCE_FROM_WP/;
}
} else {
die "$ENV{HOME}/.wpbackup: $!";
}
if( $SOURCE_FROM_WP ){
# Let's look into the wordpress config file for credentials
die "WPLOC undefined" unless defined $WPLOC;
die "$WPLOC: $!" unless -d "$WPLOC";
die "$WPLOC/wp-config.php: $!" unless -e "$WPLOC/wp-config.php";
$WPUN = extract_from_config( "$WPLOC/wp-config.php" => 'DB_USER' ) or die "Could not find DB_USER in $WPLOC/wp-config.php";
$WPPW = extract_from_config( "$WPLOC/wp-config.php" => 'DB_PASSWORD' ) or die "Could not find DB_PASSWORD in $WPLOC/wp-config.php";
$WPHN = extract_from_config( "$WPLOC/wp-config.php" => 'DB_HOST' ) or die "Could not find DB_HOST in $WPLOC/wp-config.php";
$WPDB = extract_from_config( "$WPLOC/wp-config.php" => 'DB_NAME' ) or die "Could not find DB_NAME in $WPLOC/wp-config.php";
}
die "WPUN undefined" unless defined $WPUN;
die "WPPW undefined" unless defined $WPPW;
die "WPDB undefined" unless defined $WPDB;
die "WPHN undefined" unless defined $WPHN;
die "WPLOC undefined" unless defined $WPLOC;
# Execute the MYSQLDUMP
my $command = "mysqldump --single-transaction --add-drop-table -h $WPHN -u $WPUN -p$WPPW $WPDB | bzip2 -c > $ENV{HOME}/wordpress-backup.sql.bz2";
`$command`;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment