php如何複製文件夾?

php只有複製文件函數copy()。閒來無事用遞歸寫了一個複製目錄的遞歸函數來練練手,還花了我不少的時間。看來還是得勤練習多思考。


<?php
/*
複製當前目錄下所有的文件去目標文件夾
$cpath 當前目錄
$dpath 目標目錄
$type all複製當前所有文件去目標目錄,dir複製所有文件至同一目錄
$i 用來統計數量總
*/
function copydir_user($cpath,$dpath,&$i,$type='all'){
	if($i == 0){
		if(!($cpath = judge_dir($cpath,true))){
			return false;
		}
		$dpath = judge_dir($dpath,false);
	}

	$handle = opendir($cpath);
	while (false !== ($file = readdir($handle))) {
		if($file!='.'&&$file!='..'){
			if(is_dir($cpath.$file)){
				$scpath = $cpath.$file.'/';
				$sdpath = $dpath;
				if($type == 'dir'){
					$sdpath = $dpath.$file.'/';
					$sdpath = judge_dir($sdpath,false);
				}
				copydir_user($scpath,$sdpath,$i,$type);
			}else{
				$current = $cpath.$file;
				$source = $dpath.$file;
 				copy($current,$source);
				$i++;
			}
	   }
   
	}
}

function judge_dir($dirname,$tips=true){
	if(substr($dirname,strlen($dirname)-1) != '/'){
		$dirname.='/';		
	}
	if(!file_exists($dirname)){
		if($tips){
			echo 'directory is not exists';
			return false;
		}else{
			mkdir($dirname);
		}
	}
	return $dirname;

}

$des_path='C:/Users/alex/Desktop/test';//目標目錄
$cur_path = 'E:/xampp/htdocs/bbs/api'; //當前目錄
$i=0;
copydir_user($cur_path,$des_path,$i,'dir');
echo $i;


發佈了38 篇原創文章 · 獲贊 12 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章