php:两个文件夹递归地比较,没有的文件自动复制过去

仿站时,通常默认模板文件和新的模板文件大部分都是一样的,下面代码可以用于比较文件是否缺失(和默认模板做比较)

如果缺失自动复制过去~~

 1 <?php
 2 /**
 3  * used:新模板和default模板比较,如果新模板没有的文件自动从default模板复制过去
 4  * @param type $defaultPath 默认模板路径
 5  * @param type $templetPath 当前模板路径
 6  * @return boolean
 7  */
 8 $templetName = 'default2';
 9 $defaultPath = dirname(__FILE__) . '\res\front\default';//默认文件夹路径
10 $templetPath = substr($defaultPath,0,-7).$templetName;
11 checkFileAndCopy($defaultPath, $templetPath);
12 function checkFileAndCopy($defaultPath, $templetPath) {
13     if (!is_dir($defaultPath)) {
14         echo '默认模板路径没有存在!!!';
15         return false;
16     }
17     $defaultPath = rtrim(str_replace('\\', '/', $defaultPath), '/');
18     $templetPath = rtrim(str_replace('\\', '/', $templetPath), '/');
19     $files = scandir($defaultPath);
20     foreach ($files as $file) {
21         if (in_array($file, array('.', '..'))) {
22             continue;
23         }
24         $fileFrom = $defaultPath . '/' . $file;
25         $fileTo = $templetPath . '/' . $file;
26         if (is_dir($fileFrom)) {
27             @mkdir($fileTo);
28             checkFileAndCopy($fileFrom, $fileTo);
29         } else {
30             if (file_exists($fileTo)) {
31                 continue;
32             } else {
33                 copy($fileFrom, $fileTo);
34                 echo $templetPath . '/新增文件:' . $file . "<br />";
35             }
36         }
37     }
38     return true;
39 }
40 ?>