ritter.vg
tech > code > adventures in code > Bastardizing a Backup
2 Nov 2008 16:11 EST
the goal
The goal of this code was simple. I wanted to be able to either hit a PHP page on a webserver, or plug the pinging of it into a cron script, and the PHP file would dump the MySQL databases, and automatically upload them to another server for backup.
what went wrong
Two things went wrong.
  1. I couldn't get the upload to work. I couldn't get the FTP code in the PHP script to upload the file - it was just creating a 0-sized file.
  2. I wasn't paying attention to what I was doing. I was setting up Compiz-Fusion on my new gentoo box while doing this, and thus the code was written between compiles. I wasn't thinking about anything other than "okay that won't work, what will? hm yea I think that might do it..."
the outcome
the code

This code contains numerous security holes, in addition to a horrible design. You should not use it.

backup.php

$db_host="localhost";
$db_user="";
$db_pass="";
  
$db_connection = mysql_connect($db_host, $db_user, $db_pass) or die("Could not connect to database");
$dbs = mysql_list_dbs($db_connection) or die("Could not list databases");
$dblist = "";
while($db_row = mysql_fetch_object($dbs))
{
	$db = $db_row->Database;
	$dblist .= " " .$db;
}
mysql_close($db_connection);

$filename = "mysqlbackup-".date("Y-m-d--G-i-s");
exec("mysqldump --opt --u=$db_user --password=$db_pass --databases $dblist > $filename", $out);
exec("gzip $filename");

$url = "http://backupserver/wget.php?file=".urlencode("http://thisserver/".$filename.".gz")."&callback=".urlencode("http://thisserver/callback.php?file=".$filename.".gz");
$urlH = fopen($url, 'r');
while($l = fread($urlH, 32764));
fclose($urlH);

wget.php

$get = urldecode($_GET['file']);
if(strlen($get) < 3)
	die("no file specified");
if(strpos($get, "mysqlbackup") === false)
	die("sneaky sneaky!");
$callback = urldecode($_GET['callback']);
if(strlen($callback) < 3)
	die("no callback specified");

$time = date("Y-m-d--G-i-s-");

$hsl = fopen($time."handshakelist.txt", 'w') or die("could not open handshakelist");
fwrite($hsl, $get . "\n");
fwrite($hsl, $callback);
fclose($hsl);

system("wget -b -a wgetscript.log -nv -i ".$time."handshakelist.txt")

unlink($time."handshakelist.txt");

callback.php

$file = urldecode($_GET['file']);
if(strpos($file, "mysqlbackup") === false)
	die("sneaky sneaky!");

unlink($file);

Comments
Add a comment...
required
required, hidden, gravatared

required, markdown enabled (help)
you type:you see:
*italics*italics
**bold**bold
[stolen from reddit!](http://reddit.com)stolen from reddit!
* item 1
* item 2
* item 3
  • item 1
  • item 2
  • item 3
> quoted text
quoted text
Lines starting with four spaces
are treated like code:

    if 1 * 2 < 3:
        print "hello, world!"
Lines starting with four spaces
are treated like code:
if 1 * 2 < 3:
    print "hello, world!"