从当前目录和子目录检索所有文件
我想使用下面的函数来检索文件夹和子文件夹中的所有文件,不知道为什么它没有返回任何结果。从当前目录和子目录检索所有文件
function listDirectory($path){
$ret = array();
function listFolderFiles($dir){
global $ret;
if (is_dir($dir) !== true) {
return false;
}
$ffs = scandir($dir);
unset($ffs[array_search('.', $ffs, true)]);
unset($ffs[array_search('..', $ffs, true)]);
foreach($ffs as $ff){
$ret[] = $ff;
if(is_dir($ff)) {
listFolderFiles($dir.'/'.$ff);
}
}
return $ret;
}
listFolderFiles($path);
return $ret;
}
它返回null
因为代码的执行在这里停止
if (count($ffs) < 1) {
return;
}
这主要是因为你可以放置一个给定的$path
值可能是一个空的[目录]的意思,没有[文件]或[目录]。
你的方法listDirectory
将返回array
如果有$path
实际上是包含无论是file
或directory
目录。
如果需要,您可以先添加另一个验证,然后再调用scandir
方法。
function listFolderFiles($dir) {
global $ret;
if (is_dir($dir) !== true) {
return false;
}
$ffs = scandir($dir);
// Rest of code
}
希望这有助于您的情况。
非常感谢eeya,我更改了我的代码,但仍然无法工作,请查看更新的代码。 –
当你调试该方法时,你得到了什么结果? '的var_dump(listDirectory($ PATH));退出;' – eeya
目录数组中的秋天文件和文件夹数组(758) –
非常感谢您的帮助,排序。
var_dump(listDirectory("../../../../wp-content/uploads/"));exit;
function listDirectory($path){
//var_dump($path);exit;
if(!file_exists ($path)) {
var_dump("File doesn't exist");exit;
}
$ret = array();
function listFolderFiles($dir){
global $ret;
if (is_dir($dir) !== true) {
return false;
}
$ffs = scandir($dir);
unset($ffs[array_search('.', $ffs, true)]);
unset($ffs[array_search('..', $ffs, true)]);
foreach($ffs as $ff){
if(is_dir($dir.'/'.$ff)) {
listFolderFiles($dir.'/'.$ff);
} else {
$ret[] = $ff;
}
}
return $ret;
}
return listFolderFiles($path);
}
'$ ret = array();返回$ ret':是否有这个'method'需要这个变量的原因? – eeya
好点,我将在一秒内更改我的代码,基本上,$ ret变量将是将保存所有文件的数组,并且这需要由函数返回。请查看更新的代码 –