php實現(xiàn)比較兩個文件夾異同的方法
本文實例講述了php實現(xiàn)比較兩個文件夾異同的方法。分享給大家供大家參考。具體分析如下:
要求:
只能使用命令行,比較兩個文件夾的不同,包括文件的差異。
思考:
雖然linux下有diff。。。。還是用php吧,代碼改的方便,速度也很快,以下排除了.svn目錄的比較
文件要比較md5校驗和
思路:
1)把第一路徑作為標準路徑,列出第1個路徑中有的,第2個路徑中沒有的文件或文件夾,或者是不同的文件。
2)然后,列出第2個路徑中有的,第1個路徑中卻不存在的文件和文件夾。
調(diào)用示例:
php compare_folder.php /home/temp/2 /home/temp/55
代碼如下:
<?php
/**
* 工具文件
* 目的在于遞歸比較兩個文件夾
*
* 調(diào)用示例
* php compare_folder.php /home/temp/2 /home/temp/55
*
*/
//參數(shù)確定
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('參數(shù)必須是絕對路徑');
}
$dir = preg_replace('#/$#', '', $dir);
return $dir;
}
/**
* 公用函數(shù),會調(diào)用一個遞歸方法實現(xiàn)比較
*
* @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);
}
/**
* 真實的函數(shù),私有函數(shù)
*
* @param string $dir1 路徑1,是標準
* @param string $base_dir1 不變的參數(shù)路徑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程序設計有所幫助。
相關文章
PHP基于關聯(lián)數(shù)組20行代碼搞定約瑟夫問題示例
這篇文章主要介紹了PHP基于關聯(lián)數(shù)組20行代碼搞定約瑟夫問題,結合具體實例分析了php使用關聯(lián)數(shù)組解決約瑟夫問題的相關操作技巧,需要的朋友可以參考下2017-11-11
PHP壓縮html網(wǎng)頁代碼(清除空格,換行符,制表符,注釋標記)
如果提高網(wǎng)頁加載速度,需要怎么優(yōu)化是一個問題,yahoo曾經(jīng)搞了一個優(yōu)化36條。其實網(wǎng)頁優(yōu)化的方法還是很多很多的。下面扯一下關于減小頁面體積來提高前端加載速度的方法2012-04-04
PHP5.0 TIDY_PARSE_FILE緩沖區(qū)溢出漏洞的解決方案
這篇文章主要給大家介紹了關于PHP5.0 TIDY_PARSE_FILE緩沖區(qū)溢出漏洞的解決方案,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2018-10-10

