To search for specific files within a given directory, including multiple nested subdirectories, you can use a recursive function to achieve this. Below is an example of PHP code that recursively searches for files within a specified directory:
function searchFiles($dir, $filename) {
// 遍历目录
$files = scandir($dir);
foreach ($files as $file) {
if ($file === '.' || $file === '..') {
continue;
}
$path = $dir . '/' . $file;
if (is_dir($path)) {
// 如果是目录,则递归调用searchFiles函数
searchFiles($path, $filename);
} else {
// 如果是文件,则判断是否与指定文件名匹配
if ($file === $filename) {
echo $path . "\n";
}
}
}
}
// 调用searchFiles函数进行查询
$searchDir = '/path/to/directory'; // 替换为你要查询的目录路径
$searchFile = 'example.txt'; // 替换为你要查询的文件名
searchFiles($searchDir, $searchFile);将/path/to/directoryReplace this with the directory path you wish to query.example.txtReplace this with the filename you wish to search for. This function will iterate through all files in the specified directory and its subdirectories and print the file paths that match the given filename.
Please note that the above code only provides basic query functionality; if you require more complex query conditions or need to process the query results, you can modify it according to your specific requirements.
new release:
function searchFiles($dir, $filename) {
// 遍历目录
$files = scandir($dir);
foreach ($files as $file) {
if ($file === '.' || $file === '..') {
continue;
}
$path = $dir . '/' . $file;
if (is_dir($path)) {
// 如果是目录,则递归调用searchFiles函数
$result = searchFiles($path, $filename);
if ($result !== false) {
return $result; // 如果找到匹配的文件,则直接返回路径
}
} else {
// 如果是文件,则判断是否与指定文件名匹配
if ($file === $filename) {
return $path; // 找到匹配的文件,返回路径
}
}
}
return false; // 循环结束时仍未找到匹配的文件,返回false
}