Page 1 of 1

moving folder and folder contents

Posted: Wed Mar 22, 2006 10:38 am
by gurjit
hi,


what command do i use to copy an existing folder with sub folders and files to a new directory?

even better - can i take an existing folder with sub folders and files, and cut and paste it into a new directory?

Posted: Wed Mar 22, 2006 10:43 am
by feyd
in pure php? You'll have to build a file list and directory list and either rename() or copy() all the files after rebuilding the directory tree.

Posted: Wed Mar 22, 2006 12:14 pm
by Burrito
You'll probably want to write a recursive function to drill into the folders and move everything within.

Posted: Thu Mar 23, 2006 4:06 am
by gurjit
I thought there might be a copy and paste command but after some research, no luck.

how ever I done it and use the functions below, which may be of use to someone in the future

Code: Select all

<?php
//function removes a directory and its sub directories
function rmdirr($dirname) 
{ 
    // Sanity check 
    if (!file_exists($dirname)) { 
        return false; 
    } 
  
    // Simple delete for a file 
    if (is_file($dirname) || is_link($dirname)) { 
        return unlink($dirname); 
    } 
  
    // Loop through the folder 
    $dir = dir($dirname); 
    while (false !== $entry = $dir->read()) { 
        // Skip pointers 
        if ($entry == '.' || $entry == '..') { 
            continue; 
        } 
  
        // Recurse 
        rmdirr($dirname . DIRECTORY_SEPARATOR . $entry); 
    } 
  
    // Clean up 
    $dir->close(); 
    return rmdir($dirname); 
} 



//function copies a directory and its sub directories
function copyr($source, $dest) 
{ 
    // Simple copy for a file 
    if (is_file($source)) { 
        return copy($source, $dest); 
    } 
  
    // Make destination directory 
    if (!is_dir($dest)) { 
        mkdir($dest); 
		chmod ("$dest" ,0777);
    } 
  
    // Loop through the folder 
    $dir = dir($source); 
    while (false !== $entry = $dir->read()) { 
        // Skip pointers 
        if ($entry == '.' || $entry == '..') { 
            continue; 
        } 
  
        // Deep copy directories 
        if ($dest !== "$source/$entry") { 
            copyr("$source/$entry", "$dest/$entry"); 
			chmod ("$dest/$entry" ,0777);
        } 
    } 
  
    // Clean up 
    $dir->close(); 
    return true; 
} 

?>