PHP Recursive Backup of Directories

PHP Recursive Backup of Directories

 
 

This script can be used to make backup of entire directories and subdirectories in our servers, you can use the script in conjunction with cronjobs

//specify the source dir and target dir
$src = $_SERVER['DOCUMENT_ROOT'].'/test/backup/dir1';
$dst = $_SERVER['DOCUMENT_ROOT'].'/test/backup/dir2';

function recurse_copy($src,$dst) { 
    $dir = opendir($src); 
    @mkdir($dst); 
    while(false !== ( $file = readdir($dir)) ) { 
        if (( $file != '.' ) && ( $file != '..' )) { 
            if ( is_dir($src . '/' . $file) ) { 
                recurse_copy($src . '/' . $file,$dst . '/' . $file); 
            } 
            else { 
                copy($src . '/' . $file,$dst . '/' . $file); 
            } 
        } 
    } 
    closedir($dir); 
} 

//execute the command
recurse_copy($src,$dst);

If you want to remove the old content from the directory you can use this recursive function that removes all files and folders from the specified directory

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

tags: php recursive backup files directory


We use our own cookies and third-party cookies to improve our services, show products based on your preferences, analyse the browsing habits of our users, and enable interaction with social networks. Continuing to browse our sites implies full acceptance of their use. You can change your cookie setting or get more information here: Cookies policy .