0

What would be the most elegant way to express the following in PHP:

  • Look into the parent directory for a file called 'config.php'.
  • If it is there, include it.
  • It its not, look at the next higher level for a file called 'config.php'.
  • And so on, until you have either found the root 'config.php', or have reached some defined endpoint (e.g. DOCUMENT_ROOT).

Are there any predefined functions or "inclusion strategies" to serve that purpose, or would I have to implement this snippet myself?

Mischa
  • 623
  • 5
  • 17
  • You can use [`glob`](https://www.php.net/manual/en/function.glob.php) to retrieve a listing for a matching file pattern. Then you can parse that listing to find your next matching entry if you have multiple matches – Roman Oct 03 '21 at 08:29
  • 2
    Does this answer your question? [php glob - scan in subfolders for a file](https://stackoverflow.com/questions/17160696/php-glob-scan-in-subfolders-for-a-file) – Roman Oct 03 '21 at 08:29
  • I am not so sure `glob` scanning subfolders is such a good idea here. That would be going down the path from top to bottom, whereas you want to move into the other direction here. Let's say the current path was `/foo/bar/baz`, that's three folders to check in, if we go from bottom to top. But what if that `bar` folder had "sibling" folders on the same level - hundreds or thousands of them? A `glob` looking "from top to bottom" would have to search _all_ of those for the file, even if we would not be interested in any we'd find in any of those sibling folders of `bar` to begin with. – CBroe Oct 04 '21 at 08:36
  • I'd probably rather write my own loop. Check if the file exists on the current level, if not move up one by preceding the current relative path with `../`. Then use `realpath` on that, and check if the result is still within your "base path", by checking if the former _starts with_ the latter. Once that isn't the case any more, time to break off the loop at this point. – CBroe Oct 04 '21 at 08:38

0 Answers0