php目录间拷贝文件方法

项目中需要从不同文件夹中同步文件,自己写了个小方法,备注一下

设计思路 

1.检查拷贝文件夹是否存在。

2.逐级检查子文件夹内文件

3.检查各个文件夹内文件

4.检查目标目录路径是否存在,不存在时创建同名文件夹

5.拷贝到目标目录。

function finddir($path = '') {
	//切换当前路径(递归用)
	chdir ( $path );
	$base_path = getcwd ();
	//判断路径是否存在
	if (is_dir ( $base_path )) {
		//打开目录句柄。
		$dir = opendir ( $base_path );
		while ( ($file = readdir ( $dir )) !== false ) {
			//排除根目录路径('.','..')
			if (! in_array ( $file, array (".", ".." ) )) {
				//文件拷贝
				if (is_file ( $file )) {
					//拷贝目标目录
					$aim_path = str_replace ( 'downfile', 'copyfile', $base_path );
					//判断目录是否存在,如果否,创建目录。
					if (! is_dir ( $aim_path )) {
						mkdir ( $aim_path, 0777, TRUE );
					}
					//拷贝到指定目录
					copy ( $file, $aim_path . '/' . $file );
				}
				//查找子文件夹
				if (is_dir ( $file )) {
					finddir ( $file );
					chdir ( '../' );
				}
			}
		}
		//关闭目录句柄
		closedir ( $dir );
	}
}


原文地址:https://www.cnblogs.com/y0umer/p/3838867.html