Backup script for freehosting

zulhadi.rahmat51

New Member
Messages
2
Reaction score
1
Points
0
Dear guys,

Since there's no backup service on cpanel for free hosting. Here's the script to backup your public_html, public_ftp and any target you want to backup. This is very simple script with simple step: copy to backup dir --> compress --> delete old one. You can modify and make it as you need.

Code:
<?php
define('DS', DIRECTORY_SEPARATOR); // ==== SLASH

/* *********** EDIT HERE ***************** */

define('BKUP_DIR', "/home/xxxx/_BACKUP"); // ===== YOUR BACKUP WILL BE HERE
define('WEBROOT_DIR', "/home/xxxx/public_html"); // ===== YOUR WEB ROOT DIRECTORY 
define('FTPROOT_DIR', "/home/xxxx/public_ftp");// ===== YOUR FTP ROOT DIRECTORY

/* *************************************** */

// =========== COPY RECURSIVE ===========
    function copy_r( $path, $dest ) {
        if( is_dir($path) ){
            @mkdir( $dest );
            $objects = scandir($path);
            if( sizeof($objects) > 0 ){
                foreach( $objects as $file ) {
                    if( $file == "." || $file == ".." )
                        continue;
                    // go on
                    if( is_dir( $path.DS.$file ) ) {
                        copy_r( $path.DS.$file, $dest.DS.$file );
                    }
                    else{
                        copy( $path.DS.$file, $dest.DS.$file );
                    }
                }
            } return true;
        } elseif( is_file($path) ) {
            return copy($path, $dest);
        } else {
            return false;
        }
    }

// =========== DELETE RECURSIVE ==========
    function del_r($dir) {
       if (is_dir($dir)) {
          $objects = scandir($dir);
          foreach ($objects as $object) {
             if ($object != "." && $object != "..") {
                if (filetype($dir."/".$object) == "dir") del_r($dir."/".$object); else unlink($dir."/".$object);
             }
          }
       reset($objects);
       rmdir($dir);
       }
    }

// ========== COMPRESS RECURSIVE =========
    function comp_r($source, $destination) {
           if (!extension_loaded('zip') || !file_exists($source)) {
            return false;
        }

        $zip = new ZipArchive();
        if (!$zip->open($destination, ZIPARCHIVE::CREATE)) {
            return false;
        }
        $source = str_replace('\\', '/', realpath($source));
        if (is_dir($source) === true) {
            $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);
            foreach ($files as $file) {
                $file = str_replace('\\', '/', realpath($file));
                if (is_dir($file) === true) {
                    $zip->addEmptyDir(str_replace($source . '/', '', $file . '/'));
                }
                else if (is_file($file) === true) {
                    $zip->addFromString(str_replace($source . '/', '', $file), file_get_contents($file));
                }
            }
        }
        else if (is_file($source) === true) {
            $zip->addFromString(basename($source), file_get_contents($source));
        }
        return $zip->close();
    }

// =========== BACKUP ===========
    function bkup($src, $bkup_name){
        copy_r($src, BKUP_DIR.DS.$bkup_name);
        comp_r(BKUP_DIR.DS.$bkup_name, BKUP_DIR.DS.$bkup_name.".zip");
        del_r(BKUP_DIR.DS.$bkup_name);
    }

// =============== ACTION =================
/* ********* Create Backup Here ******** */
$now = date(Ymd);
bkup(WEBROOT_DIR, "WEB_".$now);
bkup(FTPROOT_DIR, "FTP_".$now);
?>

For other backup you can modify the "bkup" function. Actually this only for file backup, I'm on working for MySQL backup script. You can run it via cronjob, as what I did. Just set your cronjob every month, six month, every year or whenever you want.

Code:
30     03     1     *     *     php -f /PATH/TO/SCRIPT/backup.php

You are very welcome to modify, develope and improve this script to better one. Dont hesitate to share it also.
See u around.

_ZR_

---------- Post added at 04:45 AM ---------- Previous post was at 04:29 AM ----------

PS: I'm also working on adding mysql backup script and auto send to other server via FTP :smile:
 

misson

Community Paragon
Community Support
Messages
2,572
Reaction score
72
Points
48
The recursion can also be handled by the SPL classes RecursiveDirectoryIterator and RecursiveIteratorIterator.

PHP:
function copy_r($path, $destination) {
    # ensure paths end in "/"
    $path = preg_replace('%/?$%', '/', $path);
    $destination = preg_replace('%/?$%', '/', $destination);
    
    $dir = new RecursiveDirectoryIterator($path);
    $dir->setFlags(FilesystemIterator::SKIP_DOTS);
    $files = new RecursiveIteratorIterator($dir, RecursiveIteratorIterator::SELF_FIRST);
    $pathLen = strlen($path);
    
    foreach ($files as $from => $file) {
        $to = substr_replace($from, $destination, 0, $pathLen);
        if ($file->isDir()) {
            mkdir($to);
        } else {
            copy($from, $to);
        }
    }
}

function del_r($base) {
    $dir = new RecursiveDirectoryIterator($base);
    $dir->setFlags(FilesystemIterator::SKIP_DOTS);
    $files = new RecursiveIteratorIterator($dir, RecursiveIteratorIterator::CHILD_FIRST);
    foreach ($files as $path => $file) {
        if ($file->isDir()) {
           rmdir($path);
        } else {
           unlink($path);
        }
    }
}

Better would be to use rsync, though as far as I know it isn't supported on the X10 free hosts. csync looks to be a viable alternative, as are lftp and ncftp. All would run on the backup server and fetch the files from the site to be backed up. Unlike rsync and the backup script, I don't believe these will compress the backup for transfer.
 

misson

Community Paragon
Community Support
Messages
2,572
Reaction score
72
Points
48
Enough with the contentless posts. If you guys want to thank someone, click the "Like" link on the post. Otherwise, it's just noise.
 

alfred4w

New Member
Messages
3
Reaction score
0
Points
0
Dear guys,

Since there's no backup service on cpanel for free hosting. Here's the script to backup your public_html, public_ftp and any target you want to backup. This is very simple script with simple step: copy to backup dir --> compress --> delete old one. You can modify and make it as you need.

Code:
<?php
define('DS', DIRECTORY_SEPARATOR); // ==== SLASH

/* *********** EDIT HERE ***************** */

define('BKUP_DIR', "/home/xxxx/_BACKUP"); // ===== YOUR BACKUP WILL BE HERE
define('WEBROOT_DIR', "/home/xxxx/public_html"); // ===== YOUR WEB ROOT DIRECTORY 
define('FTPROOT_DIR', "/home/xxxx/public_ftp");// ===== YOUR FTP ROOT DIRECTORY

/* *************************************** */

// =========== COPY RECURSIVE ===========
    function copy_r( $path, $dest ) {
        if( is_dir($path) ){
            @mkdir( $dest );
            $objects = scandir($path);
            if( sizeof($objects) > 0 ){
                foreach( $objects as $file ) {
                    if( $file == "." || $file == ".." )
                        continue;
                    // go on
                    if( is_dir( $path.DS.$file ) ) {
                        copy_r( $path.DS.$file, $dest.DS.$file );
                    }
                    else{
                        copy( $path.DS.$file, $dest.DS.$file );
                    }
                }
            } return true;
        } elseif( is_file($path) ) {
            return copy($path, $dest);
        } else {
            return false;
        }
    }

// =========== DELETE RECURSIVE ==========
    function del_r($dir) {
       if (is_dir($dir)) {
          $objects = scandir($dir);
          foreach ($objects as $object) {
             if ($object != "." && $object != "..") {
                if (filetype($dir."/".$object) == "dir") del_r($dir."/".$object); else unlink($dir."/".$object);
             }
          }
       reset($objects);
       rmdir($dir);
       }
    }

// ========== COMPRESS RECURSIVE =========
    function comp_r($source, $destination) {
           if (!extension_loaded('zip') || !file_exists($source)) {
            return false;
        }

        $zip = new ZipArchive();
        if (!$zip->open($destination, ZIPARCHIVE::CREATE)) {
            return false;
        }
        $source = str_replace('\\', '/', realpath($source));
        if (is_dir($source) === true) {
            $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);
            foreach ($files as $file) {
                $file = str_replace('\\', '/', realpath($file));
                if (is_dir($file) === true) {
                    $zip->addEmptyDir(str_replace($source . '/', '', $file . '/'));
                }
                else if (is_file($file) === true) {
                    $zip->addFromString(str_replace($source . '/', '', $file), file_get_contents($file));
                }
            }
        }
        else if (is_file($source) === true) {
            $zip->addFromString(basename($source), file_get_contents($source));
        }
        return $zip->close();
    }

// =========== BACKUP ===========
    function bkup($src, $bkup_name){
        copy_r($src, BKUP_DIR.DS.$bkup_name);
        comp_r(BKUP_DIR.DS.$bkup_name, BKUP_DIR.DS.$bkup_name.".zip");
        del_r(BKUP_DIR.DS.$bkup_name);
    }

// =============== ACTION =================
/* ********* Create Backup Here ******** */
$now = date(Ymd);
bkup(WEBROOT_DIR, "WEB_".$now);
bkup(FTPROOT_DIR, "FTP_".$now);
?>

For other backup you can modify the "bkup" function. Actually this only for file backup, I'm on working for MySQL backup script. You can run it via cronjob, as what I did. Just set your cronjob every month, six month, every year or whenever you want.

Code:
30     03     1     *     *     php -f /PATH/TO/SCRIPT/backup.php

You are very welcome to modify, develope and improve this script to better one. Dont hesitate to share it also.
See u around.

_ZR_

---------- Post added at 04:45 AM ---------- Previous post was at 04:29 AM ----------

PS: I'm also working on adding mysql backup script and auto send to other server via FTP :smile:
very nice help me a lot
 

zulhadi.rahmat51

New Member
Messages
2
Reaction score
1
Points
0
Dear guys,

Since there's no backup service on cpanel for free hosting. Here's the script to backup your public_html, public_ftp and any target you want to backup. This is very simple script with simple step: copy to backup dir --> compress --> delete old one. You can modify and make it as you need.

Code:
<?php
define('DS', DIRECTORY_SEPARATOR); // ==== SLASH

/* *********** EDIT HERE ***************** */

define('BKUP_DIR', "/home/xxxx/_BACKUP"); // ===== YOUR BACKUP WILL BE HERE
define('WEBROOT_DIR', "/home/xxxx/public_html"); // ===== YOUR WEB ROOT DIRECTORY 
define('FTPROOT_DIR', "/home/xxxx/public_ftp");// ===== YOUR FTP ROOT DIRECTORY

/* *************************************** */

// =========== COPY RECURSIVE ===========
    function copy_r( $path, $dest ) {
        if( is_dir($path) ){
            @mkdir( $dest );
            $objects = scandir($path);
            if( sizeof($objects) > 0 ){
                foreach( $objects as $file ) {
                    if( $file == "." || $file == ".." )
                        continue;
                    // go on
                    if( is_dir( $path.DS.$file ) ) {
                        copy_r( $path.DS.$file, $dest.DS.$file );
                    }
                    else{
                        copy( $path.DS.$file, $dest.DS.$file );
                    }
                }
            } return true;
        } elseif( is_file($path) ) {
            return copy($path, $dest);
        } else {
            return false;
        }
    }

// =========== DELETE RECURSIVE ==========
    function del_r($dir) {
       if (is_dir($dir)) {
          $objects = scandir($dir);
          foreach ($objects as $object) {
             if ($object != "." && $object != "..") {
                if (filetype($dir."/".$object) == "dir") del_r($dir."/".$object); else unlink($dir."/".$object);
             }
          }
       reset($objects);
       rmdir($dir);
       }
    }

// ========== COMPRESS RECURSIVE =========
    function comp_r($source, $destination) {
           if (!extension_loaded('zip') || !file_exists($source)) {
            return false;
        }

        $zip = new ZipArchive();
        if (!$zip->open($destination, ZIPARCHIVE::CREATE)) {
            return false;
        }
        $source = str_replace('\\', '/', realpath($source));
        if (is_dir($source) === true) {
            $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);
            foreach ($files as $file) {
                $file = str_replace('\\', '/', realpath($file));
                if (is_dir($file) === true) {
                    $zip->addEmptyDir(str_replace($source . '/', '', $file . '/'));
                }
                else if (is_file($file) === true) {
                    $zip->addFromString(str_replace($source . '/', '', $file), file_get_contents($file));
                }
            }
        }
        else if (is_file($source) === true) {
            $zip->addFromString(basename($source), file_get_contents($source));
        }
        return $zip->close();
    }

// =========== BACKUP ===========
    function bkup($src, $bkup_name){
        copy_r($src, BKUP_DIR.DS.$bkup_name);
        comp_r(BKUP_DIR.DS.$bkup_name, BKUP_DIR.DS.$bkup_name.".zip");
        del_r(BKUP_DIR.DS.$bkup_name);
    }

// =============== ACTION =================
/* ********* Create Backup Here ******** */
$now = date(Ymd);
bkup(WEBROOT_DIR, "WEB_".$now);
bkup(FTPROOT_DIR, "FTP_".$now);
?>

For other backup you can modify the "bkup" function. Actually this only for file backup, I'm on working for MySQL backup script. You can run it via cronjob, as what I did. Just set your cronjob every month, six month, every year or whenever you want.

Code:
30     03     1     *     *     php -f /PATH/TO/SCRIPT/backup.php

You are very welcome to modify, develope and improve this script to better one. Dont hesitate to share it also.
See u around.

_ZR_

---------- Post added at 04:45 AM ---------- Previous post was at 04:29 AM ----------

PS: I'm also working on adding mysql backup script and auto send to other server via FTP :smile:


Hi guys.. Thanx 4 your feedback.. And after a long long time, here is this the script for MySQL Backup, you can customize your database backup at "bkup_db" function.
Code:
// =========== DB BACKUP ============
function bkup_db($db_host,$db_user,$db_pass,$db_name,$tables = '*'){
  $link = mysql_connect($db_host,$db_user,$db_pass);
  mysql_select_db($db_name,$link);
  
  // GET ALL 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);
  }
  
  // LOOPING
  foreach($tables as $table){
    $result = mysql_query('SELECT * FROM '.$table);
    $num_fields = mysql_num_fields($result);
    
    $return.= 'DROP TABLE '.$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","[URL="file://n"]\\n",$row[$j[/URL]]);
          if (isset($row[$j])) { $return.= '"'.$row[$j].'"' ; } else { $return.= '""'; }
          if ($j<($num_fields-1)) { $return.= ','; }
        }
        $return.= ");\n";
      }
    }
    $return.="\n\n\n";
  }
  
  //SAVE SQL FILE
  $handle = fopen(BKUP_DIR.DS.'DB_'.$db_name.'_'.date(Ymd).'.sql','w+');
  fwrite($handle,$return);
  fclose($handle);
}

$db_user = "XXXXX" //==== YOUR MYSQL USERNAME
$db_pass = "XXXXX" // ===== YOUR MYSQL PASSWORD
bkup_db('localhost', $db_user, $db_pass, 'database_1'); === // BACKUP ALL TABLE ON database_1
bkup_db('localhost', $db_user, $db_pass, 'database_2'); === // BACKUP ALL TABLE ON database_2
bkup_db('localhost', $db_user, $db_pass, 'database_2', 'table_1'); === // BACKUP table_1 ON database_2


//================================================================================================================

Put the script together on the previous script, so you have a complete backup script. Then, find the backup at your BACKUP_DIR.

CU.

---------- Post added at 04:04 AM ---------- Previous post was at 04:02 AM ----------

Hi guys.. Thanx 4 your feedback.. And after a long long time. Here is this the script for MySQL Backup, you can customize your database backup at "bkup_db" function.

Code:
// =========== DB BACKUP ============
function bkup_db($db_host,$db_user,$db_pass,$db_name,$tables = '*'){
  $link = mysql_connect($db_host,$db_user,$db_pass);
  mysql_select_db($db_name,$link);
  
  // GET ALL 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);
  }
  
  // LOOPING
  foreach($tables as $table){
    $result = mysql_query('SELECT * FROM '.$table);
    $num_fields = mysql_num_fields($result);
    
    $return.= 'DROP TABLE '.$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","[URL="file://n"]\\n",$row[$j[/URL]]);
          if (isset($row[$j])) { $return.= '"'.$row[$j].'"' ; } else { $return.= '""'; }
          if ($j<($num_fields-1)) { $return.= ','; }
        }
        $return.= ");\n";
      }
    }
    $return.="\n\n\n";
  }
  
  //SAVE SQL FILE
  $handle = fopen(BKUP_DIR.DS.'DB_'.$db_name.'_'.date(Ymd).'.sql','w+');
  fwrite($handle,$return);
  fclose($handle);
}

$db_user = "XXXXX" //==== YOUR MYSQL USERNAME
$db_pass = "XXXXX" // ===== YOUR MYSQL PASSWORD
bkup_db('localhost', $db_user, $db_pass, 'database_1'); === // BACKUP ALL TABLE ON database_1
bkup_db('localhost', $db_user, $db_pass, 'database_2'); === // BACKUP ALL TABLE ON database_2
bkup_db('localhost', $db_user, $db_pass, 'database_2', 'table_1'); === // BACKUP table_1 ON database_2


//================================================================================================================

Put the script together on the previous script, so you have a complete backup script. Then, find the backup at your BACKUP_DIR.

CU.
 
Top