'PHP get File Directory of an included File

i have the following PHP File Structure:

dir0
    dirA    
        dirA.1    
            dirA.1.1    
                fileA.php : dirname(__FILE__).'/docs';    
        dirA.2
        ...    
    dirB    
       fileB.php: include_once("../dirA/dirA.1/dirA.1.1/fileA.php");    
    dirC    
       fileC.php: include_once("../dirA/dirA.1/dirA.1.1/fileA.php");

in the included fileA.php i use dirname(__FILE__).

i get the currect path if i call the function of fileA.php directly. BUT i get the wrong path if i call it (after include) in fileB.php and fileC.php, ...etc!

how can i get the directory of the included file?

NOTE: the name of dir0(root) may change, so i don't want to use static Strings for these paths!



Solution 1:[1]

You don't get the wrong path.

An include makes the called file part of the script it has been called from, but it won't change the path PHP is pointing to. So if you call fileA from dirB, PHP is still in dirB.

But you know dirA (otherwise you can't include fileA), so chdir("../dirA/dirA.1/dirA.1.1/") will point PHP to dirA, even from fileB or file C.

You could consider working from dir0. Call fileB with dirB/fileB.php and include fileA with include "dirA/dirA.1/dirA.1.1/fileA.php". In that case you always know where you are in the tree: in dir0.

Edit I was wrong. If you call dirname(__FILE__); from the included fileA, it returns the path of fileA. So all you have to do at the top of fileA is:

$mypath=dirname(__FILE__);
function myfunction($path){
    echo $path;
    }

And in fileB call your function while passing $mypath:

 myfunction($mypath);

Note that you might have to do some fiddling with slashes and backslashes, depending on the system your server is running.

Solution 2:[2]

This is a good candidate for get_included_files(). This function will return a numerically indexed array containing all the files that are included. "Gets the names of all files that have been included using include, include_once, require or require_once."
https://www.php.net/manual/en/function.get-included-files.php

You can get the directories that have included files like this:

array_map("dirname",get_included_files());

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 user18175864