phpで2つのフォルダの異同を比較する

3713 ワード

要件:
ファイルの違いを含む2つのフォルダの違いを比較するには、コマンドラインのみを使用します.
考え:
linuxの下にdiffがいますが...やはりphpを使いましょう、コードの変更の便利さ、スピードも速くて、以下は排除しました.svnディレクトリの比較
ファイルはmd 5チェックサムを比較する
考え方:
1)1番目のパスを標準パスとして,1番目のパスにある,2番目のパスにないファイルやフォルダ,あるいは異なるファイルをリストする.
2)次に、2番目のパスにある、1番目のパスに存在しないファイルとフォルダをリストします.
呼び出し例:
php compare_folder.php/home/temp/2/home/temp/55
実装:
compare_folder.phpファイル:

<?php
/**
 *     
 *              
 * 
 *     
 * php compare_folder.php /home/temp/2 /home/temp/55
 * 
 */

//    
if (count($argv) > 1 )
  $dir1 = del_postfix($argv[1]);
else 
  $dir1 = '/';

if (count($argv) > 2 )
  $dir2 = del_postfix($argv[2]);
else
  $dir2 = '/';

//        ,          。
process_compare($dir1,  $dir2,  0);
echo "===========================================================
"; // 2 process_compare($dir2 , $dir1, 1); echo "all OK
"; /** * /, * * @param unknown_type $dir * @return unknown */ function del_postfix($dir) { if (!preg_match('#^/#', $dir)) { throw new Exception(' '); } $dir = preg_replace('#/$#', '', $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 'compare: ' . $new . "
"; $other = preg_replace('#^'. $base_dir1 .'#' , $base_dir2, $new); if(is_dir($new)) { // if (!is_dir($other)) { echo '!!not found direction: '. $other. ' (' . $new .")
"; } compare_file_folder($new, $base_dir1,$base_dir2, $only_check_has) ; } else { // 1 , 2 if (!is_file($other)) { echo '!!not found file: '. $other. ' ('.$new .")
"; }elseif ($only_check_has ==0 && ( md5_file($other) != md5_file($new) ) ){ echo '!!file md5 error: '. $other. ' ('.$new .")
"; } } } } closedir($dh); } } } ?>