How To Run A Backup to FTP

From ReduxWiki

Jump to: navigation, search

Similar to others, uses cURL/SSL to download home/DB backups, but uploads them to a remote FTP Server or your choosing.

Uses an HTML form submittal.


<?php
$useSsl = false;
$sleep = 0;
$logType = 'echo';
$logFileName = '';
?>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>INPUT A TITLE</TITLE>

</HEAD>

<BODY>

<?php

if ($_SERVER['REQUEST_METHOD'] == 'POST'
	&& !empty($_POST['reseller'])
	&& !empty($_POST['whmUser'])
	&& !empty($_POST['whmPass'])
	&& !empty($_POST['ftpServer'])
	&& !empty($_POST['ftpUser'])
	&& !empty($_POST['ftpPass'])
	&& !empty($_POST['ftpDir'])
	
) {  
    set_time_limit(0);
    if (!extension_loaded('curl')) {
		dl('php_curl.' .PHP_SHLIB_SUFFIX) or die("Could not load curl extension"); 
    }    
    if($useSsl) {
		$protocol = 'https://';
        $cpPort = '2083';
        $whmPort = '2087';
        writeLog("Using SSL.\n");
    }
    else {
        $protocol = 'http://';
        $cpPort = '2082';
        $whmPort = '2086';
        writeLog("Not using SSL.\n");
    }    

    foreach($_POST as $n => $v){
        $$n = trim(strip_tags($v));
    }
    $reseller = preg_replace('/^(www\.|http:\/\|http:\/\/www\.)/i','',$reseller);

    //get the WHM 'list accounts' page
    writeLog("Retrieving WHM accounts page...\n");
    $accounts =    getAccounts();
    if(is_array($accounts)) {

        if(($connId = ftpConnect($ftpServer, $ftpUser, $ftpPass))===false){
            writeLog("Unable to connect to server. Exiting.\n");
            exit;
        }
        if(!ftpChDir($connId, $ftpDir)){
            writeLog("Unable to change directory on remote server. Exiting.\n");
            exit;
        }
        foreach($accounts as $account) {
                    
	/* THE HOME BACKUP PORTION */
            
	$fileName = 'bkup_'.str_replace('.','_',$account['cpDomain']).'_'.date('n_j_y').'.tar.gz';

	writeLog("Retrieving $fileName...\n");
	$siteBackup = getByCurl($protocol.$account['cpDomain'].':'.$cpPort.'/getbackup/'.$fileName,$account['cpUser'],$whmPass);
	writeLog("Uploading $fileName to $ftpServer...\n");
	$fp = tmpfile();
	fwrite($fp, $siteBackup);
	rewind($fp);
	if(ftp_fput($connId, $fileName, $fp, FTP_BINARY)){
		writeLog("Uploaded $fileName to $ftpServer...\n");
			}
            else {
				writeLog("Unable to uploaded $fileName to $ftpServer.\n");
            }
            fclose($fp);

            /* THE DB BACKUP PORTION */

            //get the cpanel backup page
            $cpDbPage = getByCurl($protocol.$account['cpDomain'].':'.$cpPort.'/frontend/'.$account['cpTheme'].'/backup/index.html',$account['cpUser'],$whmPass);

            //find the dbs available
            $numMatches = preg_match_all('/"\/getsqlbackup\/(.*?)"/ims',$cpDbPage,$dbMatches);

            if($numMatches > 0 && is_array($dbMatches[1])) {

                //foreach db available...
                foreach($dbMatches[1] as $dbMatch) {
                    $dbBkUp = '';

                    //get the sql backup
                    writeLog("Retrieving $cpDomain DB: $dbMatch...\n");
                    $dbBkUp = getByCurl($protocol.$account['cpDomain'].':'.$cpPort.'/getsqlbackup/'.$dbMatch,$account['cpUser'],$whmPass);
                    
                    $dbFileName = 'db_'.basename($dbMatch,'.gz').'_'.str_replace('.','_',$account['cpDomain']).'_'.date('n_j_y').'.gz';
                    
                    //save the sql backup...
                    writeLog("Uploading $dbMatch as $dbFileName to $ftpServer...\n");
                    $fp = tmpfile();
                    fwrite($fp, $dbBkUp);
                    rewind($fp);
                    if(ftp_fput($connId, $dbFileName, $fp, FTP_BINARY)){
                        writeLog("Uploaded $dbFileName to $ftpServer...\n");
                    }
                    else {
                        writeLog("Unable to upload $dbFileName to $ftpServer...\n");
                    }
                    fclose($fp);

                    sleep($sleep);
                }
            }
        }
    }
    writeLog("Done.\n");
}


?>

<FORM METHOD=POST ACTION="<?=$_SERVER['PHP_SELF'];?>">
Reseller Domain: <INPUT TYPE="text" NAME="reseller" value="<?=$reseller;?>" size="50"><br>
WHM User Name: <INPUT TYPE="text" NAME="whmUser" value="<?=$whmUser;?>"><br />
WHM Password: <INPUT TYPE="password" NAME="whmPass" value="<?=$whmPass;?>"><br />
<br />
Remote FTP Server: <INPUT TYPE="text" NAME="ftpServer" value="<?=$ftpServer;?>"><BR>
Remote FTP User Name: <INPUT TYPE="text" NAME="ftpUser" value="<?=$ftpUser;?>"><BR>
Remote FTP Password: <INPUT TYPE="password" NAME="ftpPass" value="<?=$ftpPass;?>"><BR>
Remote FTP Upload Dir: <INPUT TYPE="text" NAME="ftpDir" value="<?=$ftpDir;?>" size="50"><BR>
(Relative to home directory)<br>
<input type="submit">
</FORM>
</BODY>
</HTML>

<?php

/*** BEGIN FUNCTIONS ***/

function getByCurl($url, $user = '', $pass = '',$extra = '') {
  global $useSsl;

  $ch = curl_init();
  //tells curl to save result in a variable instead of outputing to page
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch, CURLOPT_URL, $url);  
  curl_setopt($ch, CURLOPT_USERPWD, "$user:$pass");
  curl_setopt ($ch, CURLOPT_COOKIEJAR, './cookie.txt');
  curl_setopt ($ch, CURLOPT_FOLLOWLOCATION,1);
  if(!empty($extra) && is_array($extra)){
    foreach($extra as $opt=>$val){
      switch($opt){
        case 'CURLOPT_REFERER':
          curl_setopt($ch,CURLOPT_REFERER,$val);
        break;
        case 'CURLOPT_POST':
        case 'CURLOPT_POSTFIELDS':
          curl_setopt($ch,CURLOPT_POST,1);
          curl_setopt($ch,CURLOPT_POSTFIELDS,$val);
        break;
      }
    }
  }
  if($useSsl){
    curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
  }
  $result = curl_exec($ch);
  curl_close($ch);

  return $result;
}

function writeLog($entry) {
  global $logType,$logFileName;

  $method = strtolower($logType);

  $entry = date('r').' - '.$entry;
  
  if($method == 'file') {
    $fp = fopen($logFileName,'ab');
  }
  elseif($method == 'echo'){
    if(isset($_SERVER['REQUEST_METHOD'])) {
      echo nl2br($entry);//browser
      flush();
      return;
    }
    else {
      $fp = STDOUT;//cli
    }
  }
  else {
    return;
  }
  
  fwrite($fp, $entry);

  if($method == 'file')
    fclose($fp);

  return;
}

function ftpConnect($ftpServer, $ftpUser, $ftpPass) {
$connId = ftp_connect($ftpServer);
$loginResult = ftp_login($connId, $ftpUser, $ftpPass);
if (!$connId || !$loginResult) {
  return false;
}
else{
   return $connId;
  }
}


function ftpChDir($connId, $dir) {
if(strrpos($dir, '/') == strlen($dir)  &&  strlen($dir) > 0){
  $dir = substr($dir,0,strrpos($dir, '/')-1);
}
if(ftp_pwd($connId) == $dir) return true;

$tree = explode('/', $dir);

for($i=0; $i<count($tree); $i++) {
   if($tree[$i] != '' && $tree[$i] != '/'){
     if($i == 1)
      $base = '/';
     else
      $base = '';
     if(@ftp_chdir($connId, $base.$tree[$i]) === false){
       if(ftp_mkdir($connId, $tree[$i]) === false){
                 return false;
             }
       if(@ftp_chdir($connId, $tree[$i])===false){
                 return false;
             }
      }
    }
  }
    return true;
}

function getAccounts(){
    global $protocol,$reseller,$whmPort,$whmUser,$whmPass;
    
    $accounts = array();
    $acctsPage = getByCurl($protocol.$reseller.':'.$whmPort.'/scripts2/listaccts?viewall=1',$whmUser,$whmPass);
    $int2 = preg_match_all("/<tr class=(?:tdshade2|tdshade1)>(.*?)<\/tr>/is", $acctsPage, $matches);
    if($int2 > 0 && is_array($matches[1])) {
        $i = 0;
        foreach($matches[1] as $match) {
            $account = array();
            $account = explode('</td><td>',$match);
            $accounts[$i]['cpDomain'] = strip_tags(trim($account[0]));//domain
            $accounts[$i]['cpUser'] = strip_tags(trim($account[2]));//username
            $accounts[$i]['cpTheme'] = strip_tags(trim($account[9]));//cpanel theme
            $i++;
        }
    }
    return $accounts;
}
?>



Image:Tip.png Back to How To Documents
Personal tools