Question

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?

Was it helpful?

Solution

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\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);
[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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top