2013-12-18 89 views
0

我想遞歸讀取文件夾及其子文件夾中的所有文件。在閱讀這些文件時,我想計算它們的校驗和並將它們存儲在一個數組中。在一個文件夾中的所有文件存儲sha1校驗和

在修改之前由Shef書面和提到的stack overflow的代碼,我有以下幾點 -

function listFolderFiles($dir){ 
    global $hash_array; 
    $folder = scandir($dir); 
    foreach($folder as $file){ 
     if($file != '.' && $file != '..' && $file != '.DS_Store'){ 
      if(is_dir($dir.'/'.$file)) { 
       echo "Here is a folder $file<br>"; 
       listFolderFiles($dir.'/'.$file); 
      } else { 
       echo "SHA checksum of $file - ".sha1_file($file)."<br>"; 
       $hash_array[] = $file; 
      } 
     } 
    } 
} 

然而,這個輸出是唯一的最後一個文件的腳本讀取的校驗和。任何人都可以在這裏發現問題?

+0

是否將'$ hash_array'定義爲該函數之外的數組? – ollieread

+0

@ollieread - 是的! – Namit

回答

1

我做了一個似乎修復它的改變。

echo "SHA checksum of $file - ".sha1_file($file)."<br>"; 

需要是

echo "SHA checksum of $file - ".sha1_file($dir . '/' . $file)."<br>"; 

然後,當我跑它作爲一個測試,它工作得很好。

[[email protected] test]# cat loop.php 
<?php 

$hash_array = array(); 

function listFolderFiles($dir){ 
    global $hash_array; 
    $folder = scandir($dir); 
    foreach($folder as $file){ 
     if($file != '.' && $file != '..' && $file != '.DS_Store'){ 
      if(is_dir($dir.'/'.$file)) { 
       echo "Here is a folder $file\n"; 
       listFolderFiles($dir.'/'.$file); 
      } else { 
       echo "SHA checksum of $file - ".sha1_file($dir . '/' . $file)."\n"; 
       $hash_array[] = $file; 
      } 
     } 
    } 
} 

listFolderFiles('/root/test'); 
var_dump($hash_array); 
[[email protected] test]# php loop.php 
SHA checksum of loop.php - 310cc407ff314b7fc8abed13e0a9e5a786c79d33 
SHA checksum of test.php - 9912d1cdf8b77baabdc0d007a3d5572986db44f6 
array(2) { 
    [0] => 
    string(8) "loop.php" 
    [1] => 
    string(8) "test.php" 
} 

之前作出改變sha1_file()它並吐出了錯誤的負荷,因此機會是,你得的error_reporting關閉。

相關問題