Backup script for freehosting

Discussion in 'Scripts, 3rd Party Apps, and Programming' started by zulhadi.rahmat51, Dec 12, 2011.

  1. zulhadi.rahmat51

    zulhadi.rahmat51 New Member

    Messages:
    2
    Likes Received:
    1
    Trophy 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:
     
    • Like Like x 1
  2. jfrancis79

    jfrancis79 Member Prime Account

    Messages:
    133
    Likes Received:
    1
    Trophy Points:
    18
    Is there a demo and what are the requirements?
     
  3. misson

    misson Community Paragon Community Support

    Messages:
    2,572
    Likes Received:
    72
    Trophy 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($dirRecursiveIteratorIterator::SELF_FIRST);
        
    $pathLen strlen($path);
        
        foreach (
    $files as $from => $file) {
            
    $to substr_replace($from$destination0$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($dirRecursiveIteratorIterator::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.
     
  4. pb1242883

    pb1242883 New Member

    Messages:
    13
    Likes Received:
    0
    Trophy Points:
    0
    wow buddy nice share :) i will use it :) Thank you for sharing :)
     
  5. jfrancis79

    jfrancis79 Member Prime Account

    Messages:
    133
    Likes Received:
    1
    Trophy Points:
    18
    Thank you for sharing.
     
  6. studentsofaliah52

    studentsofaliah52 New Member

    Messages:
    2
    Likes Received:
    0
    Trophy Points:
    0
    Thanks so much for sharing!!!:)
     
  7. secretlosserx21

    secretlosserx21 New Member

    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
  8. misson

    misson Community Paragon Community Support

    Messages:
    2,572
    Likes Received:
    72
    Trophy 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.
     
  9. wownoypi

    wownoypi New Member

    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    thanks for this/.. this is usefull
     
  10. alfred4w

    alfred4w New Member

    Messages:
    3
    Likes Received:
    0
    Trophy Points:
    0
    very nice help me a lot
     
  11. zulhadi.rahmat51

    zulhadi.rahmat51 New Member

    Messages:
    2
    Likes Received:
    1
    Trophy Points:
    0

    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.
     
  12. hieufpt156

    hieufpt156 New Member

    Messages:
    19
    Likes Received:
    0
    Trophy Points:
    0
  13. gnmovers

    gnmovers New Member

    Messages:
    5
    Likes Received:
    0
    Trophy Points:
    0
    thank you for the update.
     

Share This Page