Skip to content

Instantly share code, notes, and snippets.

@da1nonly
Created May 28, 2012 17:52
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save da1nonly/2820286 to your computer and use it in GitHub Desktop.
Save da1nonly/2820286 to your computer and use it in GitHub Desktop.
wordpress auto backup
<?php
/**
Backup the database of a given WordPress site.
using http://www.bin-co.com/blog/2008/10/remote-database-backup-wordpress-plugin/
*/
$site_url = 'http://yoursite.com'; //The URL of the online wordpress site
$username = 'admin'; // Admin username
$password = 'not_my_password'; // Admin password
$sync_with_local = false; // If you have a local server running and a copy of your site in it, your can use this script to automatically sync the online version with the local one. Set this to true if you want that. If this is set to false, it will just create and download the backup
// The following configuration options are needed only if $sync_with_local is set to true
$local_url = 'http://localhost/your_local_site'; //The url of the local site
$local_db_server = 'localhost'; // Mysql database server
$local_db_username = 'root'; // Mysql username
$local_db_password = ''; // Mysql password
$local_db = 'site_database_name'; // The database name for the local wordpress.
////////////// Stop Editing ////////////////////
// Login to wordpress
print "Logging into WordPress ... ";
$result = load($site_url."/wp-login.php?log=$username&pwd=" . urlencode($password) ."&wp-submit=Log In&testcookie=1", array('method'=>'post','return_info'=>true, 'curl_handle'=>false));
if(!$result['body']) { // The returned page was empty
file_put_contents('Debug/login.html', $result['body']);
print "WordPress not found at the specified location($site_url) - exiting...\n";
exit;
}
if($result['info']['url'] != $site_url . '/wp-admin/') { //The redirection was not proper.
file_put_contents('Debug/login.html', $result['body']);
print "Invalid Username or Password given for $site_url. Please correct it.\n";
exit;
}
print "done. Creating a backup ... \n";
$backup = load($site_url.'/wp-admin/edit.php?page=remote-database-backup/backup.php&exclude-spam[]=wp_comments&action=Backup', array('method'=>'get','return_info'=>true, 'curl_handle'=>$result['curl_handle'])); //Create a backup of the core tables
curl_close($backup['curl_handle']);
if(preg_match('/id="download-url" href="([^"]+)">/', $backup['body'], $download_url)) {
print "Done. Downloading $download_url[1] ...\n";
} else { // Backup file's Download link was not found.
file_put_contents('Debug/backup.html', $backup['body']);
print "Download file not found - exiting...\n";
exit;
}
$database_dump = load($download_url[1]); //Download the backup file.
$parts = array_reverse(explode('/', $download_url[1]));
$file_name = $parts[0]; //Gets the last part - we reversed the array.
print "Done. Saving it to file ... ";
file_put_contents($file_name, $database_dump); //Save it to file
print "Done\n";
if($sync_with_local) {
print "Syncing with Local database ... ";
'gzip -cd $file_name > tmp.sql';
'mysql -h $local_db_server -u $local_db_username $local_db_password $local_db < tmp.sql';
unlink('tmp.sql');
rename($file_name, "Dumps/$file_name");
mysql_connect($local_db_server,$local_db_username,$local_db_password);
mysql_select_db($local_db);
mysql_query("UPDATE wp_options SET option_value='$local_url' WHERE option_name='siteurl'");
mysql_query("UPDATE wp_options SET option_value='$local_url' WHERE option_name='home'");
mysql_query("UPDATE wp_users SET user_pass=MD5('admin') WHERE user_login='admin'");
print "Done\n";
}
print "All Done\n";
/////////////////// Library Functions //////////////////////////
/**
* Link: http://www.bin-co.com/php/scripts/load/
* Version : 2.00.A
*/
function load($url,$options=array()) {
if(!isset($options['method'])) $options['method'] = 'get';
if(!isset($options['return_info'])) $options['return_info'] = false;
if(!isset($options['cache'])) $options['cache'] = false;
$url_parts = parse_url($url);
$ch = false;
$info = array(//Currently only supported by curl.
'http_code' => 200
);
$response = '';
$send_header = array(
'Accept' => 'text/*',
'User-Agent' => 'BinGet/1.00.A (http://www.bin-co.com/php/scripts/load/)'
);
if($options['cache']) {
$cache_folder = '/tmp/php-load-function/';
if(!file_exists($cache_folder)) mkdir($cache_folder, 0777);
if(isset($options['cache_folder'])) $cache_folder = $options['cache_folder'];
$cache_file_name = str_replace(array('http://', 'https://'),'', $url);
$cache_file_name = str_replace(
array('/','\\',':','?','&','='),
array('_','_','-','.','-','_'), $cache_file_name);
$cache_file = joinPath($cache_folder, $cache_file_name); //Don't change the variable name - used at the end of the function.
if(file_exists($cache_file)) { // Cached file exists - return that.
if(!$options['return_info']) return file_get_contents($cache_file);
else return array('headers' => array('cached'=>true), 'body' => file_get_contents($cache_file), 'info' => array('cached'=>true));
}
}
///////////////////////////// Curl /////////////////////////////////////
//If curl is available, use curl to get the data.
if(function_exists("curl_init")
and (!(isset($options['use']) and $options['use'] == 'fsocketopen'))) { //Don't use curl if it is specifically stated to use fsocketopen in the options
if(isset($options['post_data'])) { //There is an option to specify some data to be posted.
$page = $url;
$options['method'] = 'post';
if(is_array($options['post_data'])) { //The data is in array format.
$post_data = array();
foreach($options['post_data'] as $key=>$value) {
$post_data[] = "$key=" . urlencode($value);
}
$url_parts['query'] = implode('&', $post_data);
} else { //Its a string
$url_parts['query'] = $options['post_data'];
}
} else {
if(isset($options['method']) and $options['method'] == 'post') {
$page = $url_parts['scheme'] . '://' . $url_parts['host'] . $url_parts['path'];
} else {
$page = $url;
}
}
if(!isset($options['curl_handle']) or !$options['curl_handle']) $ch = curl_init($url_parts['host']);
else $ch = $options['curl_handle'];
curl_setopt($ch, CURLOPT_URL, $page) or die("Invalid cURL Handle Resouce");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); //Just return the data - not print the whole thing.
curl_setopt($ch, CURLOPT_HEADER, true); //We need the headers
curl_setopt($ch, CURLOPT_NOBODY, false); //The content - if true, will not download the contents
if(isset($options['method']) and $options['method'] == 'post' and isset($url_parts['query'])) {
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $url_parts['query']);
}
//Set the headers our spiders sends
curl_setopt($ch, CURLOPT_USERAGENT, $send_header['User-Agent']); //The Name of the UserAgent we will be using ;)
$custom_headers = array("Accept: " . $send_header['Accept'] );
if(isset($options['modified_since']))
array_push($custom_headers,"If-Modified-Since: ".gmdate('D, d M Y H:i:s \G\M\T',strtotime($options['modified_since'])));
curl_setopt($ch, CURLOPT_HTTPHEADER, $custom_headers);
curl_setopt($ch, CURLOPT_COOKIEJAR, "/tmp/binget-cookie.txt"); //If ever needed...
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
if(isset($url_parts['user']) and isset($url_parts['pass'])) {
$custom_headers = array("Authorization: Basic ".base64_encode($url_parts['user'].':'.$url_parts['pass']));
curl_setopt($ch, CURLOPT_HTTPHEADER, $custom_headers);
}
$response = curl_exec($ch);
$info = curl_getinfo($ch); //Some information on the fetch
if(!isset($options['curl_handle'])) curl_close($ch); //Dont close the curl session if the curl handle is passed. We may need it later.
//////////////////////////////////////////// FSockOpen //////////////////////////////
} else { //If there is no curl
print "Curl not installed - this script needs curl to work.\n";
exit;
}
//Get the headers in an associative array
$headers = array();
if($info['http_code'] == 404) {
$body = "";
$headers['Status'] = 404;
} else {
//Seperate header and content
$separator_position = strpos($response,"\r\n\r\n");
$header_text = substr($response,0,$separator_position);
$body = substr($response,$separator_position+4);
foreach(explode("\n",$header_text) as $line) {
$parts = explode(": ",$line);
if(count($parts) == 2) $headers[$parts[0]] = chop($parts[1]);
}
}
if(isset($cache_file)) { //Should we cache the URL?
file_put_contents($cache_file, $body);
}
if($options['return_info']) return array('headers' => $headers, 'body' => $body, 'info' => $info, 'curl_handle'=>$ch);
return $body;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment