doushang2023 2013-12-18 11:40
浏览 33
已采纳

在数组中为文件夹中的所有文件存储sha1校验和

I am trying to recursively read all the files in a folder and its sub folder. Upon reading these files I want to calculate their checksum and store them in an array.

On modifying the code previously written by Shef and mentioned on stack overflow, i have the following -

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;
            }
        }
    }
}

However, the output of this is a checksum of only the last file the script reads. Can anyone spot a problem here?

  • 写回答

1条回答 默认 最新

  • dqr91899 2013-12-18 11:50
    关注

    I made one change which seemed to fix it for me.

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

    Needs to be

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

    Then when I ran it all as a test, it worked fine.

    [root@exia 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
    ";
                    listFolderFiles($dir.'/'.$file);
                } else {
                    echo "SHA checksum of $file - ".sha1_file($dir . '/' . $file)."
    ";
                    $hash_array[] = $file;
                }
            }
        }
    }
    
    listFolderFiles('/root/test');
    var_dump($hash_array);
    [root@exia 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"
    }
    

    Before making the change to sha1_file() it did spit out a load of errors, so chances are, you've got error_reporting turned off.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换