本文實例講述了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 = '/';
if (count($argv) > 2 )
$dir2 = del_postfix($argv[2]);
else
$dir2 = '/';
//檢查第一個路徑有,後者沒有或錯誤的方法。
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('#^/#', $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 . "\n";
$other = preg_replace('#^'. $base_dir1 .'#' , $base_dir2, $new);
if(is_dir($new)) {
//比較
if (!is_dir($other)) {
echo '!!not found direction: '. $other. ' (' . $new .")\n";
}
compare_file_folder($new, $base_dir1,$base_dir2, $only_check_has) ;
} else { //如果1是文件,則2也應該是文件
if (!is_file($other)) {
echo '!!not found file: '. $other. ' ('.$new .")\n";
}elseif ($only_check_has ==0 && ( md5_file($other) != md5_file($new) ) ){
echo '!!file md5 error: '. $other. ' ('.$new .")\n";
}
}
}
}
closedir($dh);
}
}
}
?>
希望本文所述對大家的php程序設計有所幫助。