Follow me on Twitter to receive updates, free scripts and ongoing announcements!

PHP copy directory from source to destination

Written by Codes Tips on May 2, 2009 – 1:02 pm -

To copy a directory source to a destination directory you will need to scan the source directory with all files and directory and copy to the destination. To accomplish this we should make a recursive function that will copy the files from source to target dir. If it is not a directory in the source dir we should just copy the file to target. If it is a directory in the source dir then we should create a new dir in the target directory and apply the same mechanism, so we need to recall again the same function.
Here is the code to do this:

<?
function copy_directory( $source, $destination ) {
	if ( is_dir( $source ) ) {
		@mkdir( $destination );
		$directory = dir( $source );
		while ( FALSE !== ( $readdirectory = $directory->read() ) ) {
			if ( $readdirectory == '.' || $readdirectory == '..' ) {
				continue;
			}
			$PathDir = $source . '/' . $readdirectory; 
			if ( is_dir( $PathDir ) ) {
				copy_directory( $PathDir, $destination . '/' . $readdirectory );
				continue;
			}
			copy( $PathDir, $destination . '/' . $readdirectory );
		}
 
		$directory->close();
	}else {
		copy( $source, $destination );
	}
}
?>

Calling the function:

copy_directory('dirnameSource','dirnameDestination');

Download copy directory code


Tags: ,
Posted in Codes, PHP/MYSQL |

One Comment to “PHP copy directory from source to destination”

  1. 25 New & Useful PHP Techniques & Tutorials Says:

    [...] 18. PHP copy directory from source to destination [...]

Leave a Comment

You must be logged in to post a comment.


Plugintaylor.com - Plugintaylor and Job Description