To find the root directory of a file in PHP, you can use the dirname()
function. This function returns the directory name component of the path. If you call it multiple times, it will eventually return the root directory.
Here's an example:
main.php259 chars14 lines
In this example, we start with the file path /var/www/html/myfile.php
. We keep calling dirname()
on the path until we reach the root directory (/
). The loop breaks when the dirname()
function returns the same path twice (indicating we have reached the root directory). The final value of $root
is the root directory path.
Note that this approach assumes Unix-style file paths (with /
as the separator). If you are working with Windows-style paths (with \
as the separator), you'll need to modify the code accordingly.
gistlibby LogSnag