Quantcast
Channel: Dropbox – Clain Dsilva's Blog
Viewing all articles
Browse latest Browse all 2

Server Backup to Dropbox with PHP – Curl – Dropbox API – Cron

$
0
0

Here is the easiest way to backup your web server with Drobox.Most of you guys have trouble setting up a secure backup option, Backing up the files to the same saver where it is hosted is again not a reliable option, You may also have space constrains. Lets see how dropbox can sort out the backup easily.
Requirements

  • Cpanel Access to your Server and Cron Job Module
  • Dropbox Api
  • PHP and Curl Support in the server you are going to implement this.

Lets divide the entire backup process into 3 functions

  1. Backu Database
  2. Backup files
  3. Upload it to dropbox.

Backup Database

There are hundreds of database backup scripts available in the Internet, you can use any of them but here I am going to use this code that I feel is more reliable and its taken from David Walsh’s blog I have slightly modified the script to optimize it

function backup_db($host,$user,$pass,$name,$dbFile,$tables = '*'){

	$link = mysql_connect($host,$user,$pass);
	mysql_select_db($name,$link);

	//get all of the tables
	if($tables == '*')
	{
		$tables = array();
		$result = mysql_query('SHOW TABLES');
		while($row = mysql_fetch_row($result))
		{
			$tables[] = $row[0];
		}
	}
	else
	{
		$tables = is_array($tables) ? $tables : explode(',',$tables);
	}

	//cycle through
	$return = '';
	foreach($tables as $table)
	{
		$result = mysql_query('SELECT * FROM '.$table);
		$num_fields = mysql_num_fields($result);

		$return.= 'DROP TABLE IF EXISTS '.$table.';';
		$row2 = mysql_fetch_row(mysql_query('SHOW CREATE TABLE '.$table));
		$return.= "\n\n".$row2[1].";\n\n";

		for ($i = 0; $i < $num_fields; $i++) 
		{
			while($row = mysql_fetch_row($result))
			{
				$return.= 'INSERT INTO '.$table.' VALUES(';
				for($j=0; $j < $num_fields; $j++) 
				{
					$row[$j] = addslashes($row[$j]);
					$row[$j] = ereg_replace("\n","\\n",$row[$j]);
					if (isset($row[$j])) { $return.= '"'.$row[$j].'"' ; } else { $return.= '""'; }
					if ($j < ($num_fields-1)) { $return.= ','; }
				}
				$return.= ");\n";
			}
		}
		$return.="\n\n\n";
	}

	//save file
	$handle = fopen($dbFile,'w+');
	fwrite($handle,$return);
	fclose($handle);

	echo " Database Backup File Created : ".$dbFile."\n";
}

Backup Server Files

Lets assume that you have your files under /home/YourPath/public_html/

function backupFiles($siteZipFile){
	shell_exec("tar -cvf ".$GLOBALS['siteZipFile']." /home/YourPath/public_html/* ");
	echo " Files Backup File Created : ".$siteZipFile." \n";
}

We are just selecting all the files under the public_html folder and creating an archive.

Drobox API Code for Backup

Now lets create the dropbox function to upload the files to dropbox

function pushToDropbox($file_path_str){
{
$url_path_str = 'https://api-content.dropbox.com/1/files_put/auto/Foldername/'.$file_path_str; 
$header = array(
"Authorization:Bearer _YourAccessToken_",
"Content-Length:".filesize($file_path_str)
);

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url_path_str);
curl_setopt($ch, CURLOPT_PUT, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);

$fh_res = fopen($file_path_str, 'r');
$file_data_str = fread($fh_res, filesize($file_path_str));
rewind($fh_res);

curl_setopt($ch, CURLOPT_INFILE, $fh_res);
curl_setopt($ch, CURLOPT_INFILESIZE, filesize($file_path_str));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

$curl_response_res = curl_exec ($ch);

echo $curl_response_res; // Server response
print_r(curl_getinfo($ch)); // Http Response
curl_close($ch);

fclose($fh_res);
}

Now Lets conclude to get the Final Code

Final Code

function backup_db($host,$user,$pass,$name,$dbFile,$tables = '*'){

	$link = mysql_connect($host,$user,$pass);
	mysql_select_db($name,$link);

	//get all of the tables
	if($tables == '*')
	{
		$tables = array();
		$result = mysql_query('SHOW TABLES');
		while($row = mysql_fetch_row($result))
		{
			$tables[] = $row[0];
		}
	}
	else
	{
		$tables = is_array($tables) ? $tables : explode(',',$tables);
	}

	//cycle through
	$return = '';
	foreach($tables as $table)
	{
		$result = mysql_query('SELECT * FROM '.$table);
		$num_fields = mysql_num_fields($result);

		$return.= 'DROP TABLE IF EXISTS '.$table.';';
		$row2 = mysql_fetch_row(mysql_query('SHOW CREATE TABLE '.$table));
		$return.= "\n\n".$row2[1].";\n\n";

		for ($i = 0; $i < $num_fields; $i++) 
		{
			while($row = mysql_fetch_row($result))
			{
				$return.= 'INSERT INTO '.$table.' VALUES(';
				for($j=0; $j < $num_fields; $j++) 
				{
					$row[$j] = addslashes($row[$j]);
					$row[$j] = ereg_replace("\n","\\n",$row[$j]);
					if (isset($row[$j])) { $return.= '"'.$row[$j].'"' ; } else { $return.= '""'; }
					if ($j < ($num_fields-1)) { $return.= ','; }
				}
				$return.= ");\n";
			}
		}
		$return.="\n\n\n";
	}

	//save file
	$handle = fopen($dbFile,'w+');
	fwrite($handle,$return);
	fclose($handle);

	echo " Database Backup File Created : ".$dbFile."\n";
}

function backupFiles($siteZipFile){
	shell_exec("tar -cvf ".$GLOBALS['siteZipFile']." /home/YourPath/public_html/* ");
	echo " Files Backup File Created : ".$siteZipFile." \n";
}

function pushToDropbox($file_path_str){
{
$url_path_str = 'https://api-content.dropbox.com/1/files_put/auto/Foldername/'.$file_path_str; 
$header = array(
"Authorization:Bearer _YourAccessToken_",
"Content-Length:".filesize($file_path_str)
);

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url_path_str);
curl_setopt($ch, CURLOPT_PUT, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);

$fh_res = fopen($file_path_str, 'r');
$file_data_str = fread($fh_res, filesize($file_path_str));
rewind($fh_res);

curl_setopt($ch, CURLOPT_INFILE, $fh_res);
curl_setopt($ch, CURLOPT_INFILESIZE, filesize($file_path_str));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

$curl_response_res = curl_exec ($ch);

echo $curl_response_res; // Server response
print_r(curl_getinfo($ch)); // Http Response
curl_close($ch);

fclose($fh_res);
}

$siteZipFile = "site_backup_".date('m_d_Y', time()).".tar.gz"; // Set the Current date in file Name
$dbFile = 'db-backup-'.date('m_d_Y', time()).'.sql'; // Set the Current date in file Name
backup_tables('localhost','dbUser','dbPwd','daName');
backupFiles($siteZipFile);
pushToDropbox($dbFile);
pushToDropbox($siteZipFile);

Setting up the Cron Job

  1. Lets name the script that you have created as “serverBackupDropbox.php”
  2. Create a folder outside your public_html folder , lets name it “backup” and place the backup script inside this folder. lets assume that the file path is now “php home/backup/serverBackupDropbox.php”
  3. Navigate to Cron module in your Cpanel and add the following command, and set your desired Cron interval.

php home/backup/serverBackupDropbox.php

You quick and easy drop-box backup solution is ready.

Hope you have enjoyed Post , Send in your feedbacks / comments.


Viewing all articles
Browse latest Browse all 2

Trending Articles