PHP: copy folder and its contents to another folder location

This snippet copies folder and its contents to another location

How to use:
Just call:
//$this->copyFolder($source,$target);
//Just make sure the variable $target is existed.
//DIRECTORY_SEPARATOR is defined as \

$this->copyFolder(‘C:\xampp\htdocs\www\files\docs\\’, ‘C:\xampp\htdocs\testing\\’);

	public function cDir($dir=null){
		if (!file_exists($dir)){
			mkdir($dir);
		}
	}

	public function copyFolder($source, $target){
		$listFiles = scandir($source);
		$arrPathInfo = pathinfo($source);
		$baseFolder = $target.DIRECTORY_SEPARATOR.$arrPathInfo['basename'];
		$this->cDir($baseFolder);
		foreach ($listFiles as $val){
			if (!(in_array($val, array('.', '..')))){
				$fullPath = $source.$val;
				$fullPath = $this->changeDirSeparator($fullPath);
				if (is_dir($fullPath)){//folder
					$this->cDir($baseFolder.DIRECTORY_SEPARATOR.$val);
					$this->copyFolder($fullPath.DIRECTORY_SEPARATOR,$baseFolder);
				}
				else if (is_file($fullPath)){//fileName
					$arrInfo = pathinfo($fullPath);
					$fileLocation = $arrInfo['dirname'];
					$fileName = $arrInfo['basename'];
					copy($fullPath, $this->changeDirSeparator($baseFolder.DIRECTORY_SEPARATOR.$fileName));
				}
			}
		}
	}

	function changeDirSeparator($path){
		$path = str_replace('/', DIRECTORY_SEPARATOR, $path);
		$path = str_replace("\\\\", DIRECTORY_SEPARATOR, $path);
		return $path;
	}

Tags:

Comments are closed.