moving folder and folder contents

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
gurjit
Forum Contributor
Posts: 314
Joined: Thu May 15, 2003 11:53 am
Location: UK

moving folder and folder contents

Post 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?
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post 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.
User avatar
Burrito
Spockulator
Posts: 4715
Joined: Wed Feb 04, 2004 8:15 pm
Location: Eden, Utah

Post by Burrito »

You'll probably want to write a recursive function to drill into the folders and move everything within.
User avatar
gurjit
Forum Contributor
Posts: 314
Joined: Thu May 15, 2003 11:53 am
Location: UK

Post 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; 
} 

?>
Post Reply