PDA

View Full Version : Move or Copy a Directory (and files and sub dirs)



tkv
12-29-2007, 07:30 PM
The code contains two functions. You need to run the MoveDirectory function pass it the source and destination directories. If copy is set to false the origional dir is removed. If it is set to true the origional dir is not deleted.

function MoveDirectory($source,$dest,$copy=false) {
//remove trailing slashes
if (substr($dest,-1) == "\\") $dest = substr($dest,0,strlen($dest)-1);
if (substr($source,-1) == "\\") $source = substr($source,0,strlen($source)-1);
if (!file_exists($source)) return FALSE;

Ensure_Sub_Directory_Exists($dest);

//now copy all the files & direcrtories to the new location and deltet them
$d = opendir($source);
while ($f = readdir($d)) {
$l = $source . "\\" . $f;
if (is_dir($l)) {
if (!($f['value']=="." || $f=="..")) {
MoveDirectory($l,$dest . "\\" . $f,$copy);
};
} else {
copy( $l ,$dest . "\\" . $f);
if (!$copy) {
//we are moving the directory so we should delete the file
unlink($l);
};
};
};
closedir($d);
if (!$copy) {
rmdir($source);
};
return TRUE;
};
function Ensure_Sub_Directory_Exists($dir) {
//When passed a directory create it
if (substr($dir,-1) == "\\") $dir = substr($dir,0,strlen($dir)-1);

if (file_exists($dir)) return TRUE;

$a = explode("\\",$dir);
while ($t = each($a)) {
$b = $t['value'];
};
$b = str_replace("\\" . $b,"",$dir);

//does $b exist?
if (!file_exists($b)) {
Ensure_Sub_Directory_Exists($b);
};
//PArent exists so make this directork exist
mkdir($dir);
return TRUE;
};