我正在尝试递归读取文件夹及其子文件夹中的所有文件。读取这些文件后,我想计算它们的校验和并将它们存储在数组中。
关于修改 Shef 之前编写并在堆栈溢出中提到的代码,我有以下内容-
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;
}
}
}
}
但是,此输出仅是脚本读取的最后一个文件的校验和。任何人都可以在这里发现问题吗?
我做了一个似乎为我修复的更改。
echo "SHA checksum of $file - ".sha1_file($file)."<br>";
需要
echo "SHA checksum of $file - ".sha1_file($dir . '/' . $file)."<br>";
然后,当我将其全部作为测试运行时,它工作正常。
[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"
}
在对sha1_file()
进行更改之前,它确实吐出了很多错误,所以很有可能,你已经关闭了error_reporting。