首頁  >  文章  >  後端開發  >  php針對目錄與檔案名稱的遞迴操作的方法

php針對目錄與檔案名稱的遞迴操作的方法

墨辰丷
墨辰丷原創
2018-06-09 15:37:441857瀏覽

本篇文章主要介紹php針對目錄與檔名的遞迴操作的方法,有興趣的朋友參考下,希望對大家有幫助。

本文實例講述了php實作比較兩個資料夾異同的方法,具體分析如下:

#要求:

只能使用命令列,比較兩個資料夾的不同,包括檔案的差異。

思考:

雖然linux下有diff。 。 。 。還是用php吧,程式碼改的方便,速度也很快,以下排除了.svn目錄的比較
檔要比較md5校驗和

思路:

1)把第一路徑當作標準路徑,列出第1條路徑中有的,第2個路徑中沒有的檔案或資料夾,或是不同的檔案。
2)然後,列出第2個路徑中有的,第1個路徑中卻不存在的檔案和資料夾。

呼叫範例:

php compare_folder.php /home/temp/2 /home/temp/55

程式碼如下:

<?php 
/** 
 * 工具文件 
 * 目的在于递归比较两个文件夹 
 * 
 * 调用示例 
 * php compare_folder.php /home/temp/2 /home/temp/55 
 * 
 */ 
//参数确定 
if (count($argv) > 1 ) 
 $dir1 = del_postfix($argv[1]); 
else 
 $dir1 = &#39;/&#39;; 
if (count($argv) > 2 ) 
 $dir2 = del_postfix($argv[2]); 
else 
 $dir2 = &#39;/&#39;; 
//检查第一个路径有,后者没有或错误的方法。 
process_compare($dir1, $dir2, 0); 
echo "===========================================================\n"; 
//检查第2个路径的多余文件夹或文件 
process_compare($dir2 , $dir1, 1); 
echo "all OK\n"; 
/** 
 * 去除路径末尾的/,并确保是绝对路径 
 * 
 * @param unknown_type $dir 
 * @return unknown 
 */ 
function del_postfix($dir) 
{ 
 if (!preg_match(&#39;#^/#&#39;, $dir)) { 
  throw new Exception(&#39;参数必须是绝对路径&#39;); 
 } 
 $dir = preg_replace(&#39;#/$#&#39;, &#39;&#39;, $dir); 
 return $dir; 
} 
/** 
 * 公用函数,会调用一个递归方法实现比较 
 * 
 * @param string $dir1 作为标准的路径 
 * @param string $dir2 对比用的路径 
 * @param int $only_check_has 为1表示不比较文件差异,为0表示还要比较文件的md5校验和 
 */ 
function process_compare($dir1, $dir2, $only_check_has){ 
 compare_file_folder($dir1, $dir1, $dir2, $only_check_has); 
} 
/** 
 * 真实的函数,私有函数 
 * 
 * @param string $dir1  路径1,是标准 
 * @param string $base_dir1 不变的参数路径2 
 * @param string $base_dir2 不变的待比较的路径2 
 * @param int $only_check_has 为1表示不比较文件差异,为0表示还要比较文件的md5校验和 
 * 
 */ 
function compare_file_folder($dir1, $base_dir1, $base_dir2, $only_check_has=0){ 
 if (is_dir($dir1)) { 
  $handle = dir($dir1); 
  if ($dh = opendir($dir1)) { 
   while ($entry = $handle->read()) { 
    if (($entry != ".") && ($entry != "..") && ($entry != ".svn")){ 
     $new = $dir1."/".$entry; 
     //echo &#39;compare: &#39; . $new . "\n"; 
     $other = preg_replace(&#39;#^&#39;. $base_dir1 .&#39;#&#39; , $base_dir2, $new); 
     if(is_dir($new)) { 
      //比较 
      if (!is_dir($other)) { 
       echo &#39;!!not found direction: &#39;. $other. &#39; (&#39; . $new .")\n"; 
      } 
      compare_file_folder($new, $base_dir1,$base_dir2, $only_check_has) ; 
     } else { //如果1是文件,则2也应该是文件 
      if (!is_file($other)) { 
       echo &#39;!!not found file:  &#39;. $other. &#39; (&#39;.$new .")\n"; 
      }elseif ($only_check_has ==0 && ( md5_file($other) != md5_file($new) ) ){ 
       echo &#39;!!file md5 error:  &#39;. $other. &#39; (&#39;.$new .")\n"; 
      } 
     } 
    } 
   } 
   closedir($dh); 
  } 
 } 
} 
?>

總結:以上就是這篇文章的全部內容,希望能對大家的學習有所幫助。

相關推薦:

php範本與js上傳外掛程式結合實作無刷新上傳的方法

php數字及數字運算驗證碼

php採用鍊式呼叫的方式連續呼叫函數的使用方法

#

以上是php針對目錄與檔案名稱的遞迴操作的方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn