note 19981 added to function.copy

From: Date: Mon, 18 Mar 2002 06:37:41 +0000
Subject: note 19981 added to function.copy
Groups: php.notes 
Request: Send a blank email to php-notes+get-27897@lists.php.net to get a copy of this message
Rec_Copy (ABOVE) needs a bit of error checking, especially if your $to_path does not completely exist. It is real touchy under Windows 98se. I did not test it fully under Unix. Rec_Copy is capable of creating one level, but not more. This lesson cost me a couple of days of scratching my head. So here is my improved code with a second function "create_path" (thanks to J. Steele for the insight). Because I use it as a remote backing-up procedure for my web server, I added $date as a handy feature to classify my backups by date: <? $date = date ("Ymd"); $from_path = "c:/program files/easyphp/ccl_www"; $to_path = "c:/tmp/cp/to/$date/ccl_www"; ##### No trailing slash ######### ##### "/" used instead of "\\" ##### ####################################### if (!is_dir($to_path)) { echo "Creating destination path\n"; create_path($to_path); } ####################################### if(!is_dir($from_path)) { echo "failed"; exit; } else { rec_copy($from_path, $to_path); echo "Files copied from $from_path and backed up to $to_path\n"; } ############################################## function rec_copy($from_path, $to_path) { if (!is_dir($to_path)) mkdir($to_path, 0777); $this_path = getcwd(); if (is_dir($from_path)) { chdir($from_path); $handle = opendir('.'); while (($file = readdir($handle)) !== false) { if (($file != ".") && ($file != "..")) { if (is_dir($file)) { rec_copy ($from_path."\\".$file, $to_path."\\".$file); chdir($from_path); } if (is_file($file)) { copy($from_path."\\".$file, $to_path."\\".$file); } } } closedir($handle); } else { echo "if (is_dir($from_path))\n"; } } ############################################## ############################################## function create_path($to_path) { $path_array = explode('/', $to_path); // split the path by directories /* echo '<pre>'; // show everything in the $path_array variable var_dump($path_array); echo '</pre>'; */ $dir=''; // start with empty directory foreach($path_array as $key => $val) { // echo "$key => $val\n"; if (!strpos($val, ':')) { // if it's not a drive letter $dir .= '/'. $val; if (!is_dir($dir)) { // echo "Not a dir: $dir\n"; if (!mkdir($dir, 0777)) echo "Failed creating directory: $dir\n"; else echo "Created directory: $dir\n"; } } } } ?> -- http://www.php.net/manual/en/function.copy.php http://master.php.net/manage/user-notes.php?action=edit+19981 http://master.php.net/manage/user-notes.php?action=delete+19981 http://master.php.net/manage/user-notes.php?action=reject+19981

« previous php.notes (#27897) next »