在目录和子目录中搜索特定文件的功能
我需要创建一个函数来搜索所有目录和子目录中的特定文件,MyFile可以在任何地方,这是我的代码:
$rootDir = realpath($_SERVER["DOCUMENT_ROOT"]) . '/file';
$filename = 'myFile';
public function searchFile($rootDir, $filename)
{
$dir = opendir($rootDir);
while ($entry = readdir($dir)) {
if (is_file("$rootDir/$entry") && $entry == $filename) {
return "$rootDir/$entry/$filename";
}
if (is_dir("$rootDir/$entry")) {
return $this->searchFile("$rootDir/$entry", $filename);
}
}
}
我的问题是我可能在子目录中使用“ myfile”以外的其他文件,而我的递归功能使我失误了因为“ $输入”正在成为文件。
这是我目录的一个例子:
-directory_1
-directory11
-randomFile.pdf
-directory_2
-myfile
-directory_3
-directory_33
-etc...
I need to create a function to search a specific file in all directories and subdirectories, myFile can be anywhere, here is my code :
$rootDir = realpath($_SERVER["DOCUMENT_ROOT"]) . '/file';
$filename = 'myFile';
public function searchFile($rootDir, $filename)
{
$dir = opendir($rootDir);
while ($entry = readdir($dir)) {
if (is_file("$rootDir/$entry") && $entry == $filename) {
return "$rootDir/$entry/$filename";
}
if (is_dir("$rootDir/$entry")) {
return $this->searchFile("$rootDir/$entry", $filename);
}
}
}
My problem is that I might have other files than 'myFile' in subdirectories and my recursive function throw me an error because '$entry' is becoming a file.
Here is an example of my directories:
-directory_1
-directory11
-randomFile.pdf
-directory_2
-myfile
-directory_3
-directory_33
-etc...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
嘿,您可以将PHP类用于此操作
您可以轻松地找到您想要的文件。
注意:我的基本目录具有“ A” sub文件夹“ B” sub文件夹具有“ C”,并且具有test.txt文件。 -
Hey you can use PHP Class for this operation
You can find with easy what you want file.
Note: My base directory have "a" sub folder has "b" sub folder has "c" and this have test.txt file. –
首先通过使用
并在每个文件夹中使用循环查看
目录中的文件列表,从而 获取目录的目录列表“ rel =“ nofollow noreferrer”>单击
first get list of directories by using
and check for file name by using for loop in each folder
To check list of files in directory refer this php function click