PHP - 在当前文件夹和子文件夹中搜索文件

时间:2017-08-07 07:11:56

标签: php file directory

我试图在PHP中检索文件的路径,但我目前卡住了。我有一个像这样的文件夹结构:

- folder 1/
- folder 2/
    - subfolder 2.1/
    - subfolder 2.2/
        - subfolder 2.2.1/
        - subfolder 2.2.2/
            - targetFile.txt
            - script1.php
            - script2.php
            - .htaccess
        - file1.php
        - file2.php
        - file3.php
        - getFile.php
        .htaccess
- Folder 3/
- Folder 4/
...

我希望在运行relative脚本时获得targetFile.txt路径getFile.php。目标文件始终位于与getFile.php位于同一父文件夹中的文件夹中。在上面的情况下,相对路径应该打印出来:

subfolder 2.2.2/targetFile.txt

这是我到目前为止所拥有的:

$dir = getcwd(); // Getting the current working dir
$files = scandir($dir); // Get all files and folders within the working dir
foreach ($files as $file) {
    if ($file = 'targetFile.txt') { // Look for a file that matches the targeted file name
        echo dirname($file);
    }
}

上面的代码没有正常工作,因为我没有获得目标文件的相对路径。

任何帮助表示感谢。

1 个答案:

答案 0 :(得分:2)

使用此代码:

<?php
    $dir = getcwd(); // Getting the current working dir
    $di = new RecursiveDirectoryIterator($dir);
    $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator('.'));
    // Get all files and folders within the working dir

    $files = [];
    foreach ($iterator as $filename => $file) {
        $path = pathinfo($filename);
        if ($path['basename'] == 'targetFile.txt') {
            echo $path['dirname'] .'<br />';
            //echo $path['dirname'], "\n";
            //echo $path['basename'], "\n";
            //echo $path['extension'], "\n";
            //echo $path['filename'], "\n"; // since PHP 5.2.0
        }
        $files[] = $filename;
    }
    //asort($files);
    //echo "<pre>"; print_r($files);die;
?>

更多信息:

http://php.net/manual/en/function.pathinfo.php

http://php.net/RecursiveDirectoryIterator