Unfortunately I don't think it is as simple as calling rename on a whole directory. You need to copy each file one at a time and create new directories as needed.
I had some permission problems while working this function out on my local machine. You probably won't have any on your webhost's server, but locally you'll need to make sure the orig directory and the directory that is going to receive the copy has read/write access.
I think there is some room for improvement in this function and I hope Daniel or Twey will comment on it. The elseif before the recursive call doesn't seem right to me for some reason, but I am not sure.
Daniel, Twey, Nile, TechieTim, please comment. Making this work is a learning experience for me too.
PHP Code:
function copy_dir($dir, $copyto) {
rtrim($dir, '/');
rtrim($copyto, '/');
// If original doesn't exist, or destination does exist
// trigger errors
if ( !is_dir($dir) || is_dir($copyto) ) {
trigger_error("Original doesn't exist or the directory you wish to create does exist",
E_USER_ERROR);
exit;
}
if ( !mkdir($copyto) ) {
trigger_error('Cannot create new directory: ' . $copyto, E_USER_ERROR);
exit;
}
$contents = scandir($dir);
for ( $x = 0; $x < count($contents); $x++) {
if ( $contents[$x] != '.' && $contents[$x] != '..' ) {
if ( is_file("$dir/$contents[$x]") ) {
copy("$dir/$contents[$x]", "$copyto/$contents[$x]");
// Something about testing for the $copyto directory here doesn't seem right
// But if you don't, you'll create an endless loop and continue to copy files
// FOREVER!
} elseif ( is_dir("$dir/$contents[$x]") && "$dir/$contents[$x]" != $copyto ) {
// Recursive call here
copy_dir("$dir/$contents[$x]", "$copyto/$contents[$x]");
}
}
}
}
copy_dir('/path_to_orig', '/path_to_new');
exit;
Bookmarks