Getting all Parent Folders of a Folder and File

I need to get all the parent folders of a File for a work. I searched on net to find easy solution for this and also to find some tips for my work. As, my work was heavily dependent on this logic, so I have given some time to it. But whatever I have found was the code related to sub-folders or tree structure of a folder. So, finally I have written this:


<?php
$i = 0;
while($currDirInLoop != 'StopAtThisFolder')
{
    if ($i == 0)
        $tmp  = dirname(__FILE__);
    else
        $tmp = $path;
    $path = realpath($tmp  . '/../');
    echo '<hr>';
    //var_dump($path);
    echo $currDirInLoop = basename($tmp);
    $i++;
    if ($i == 10) break;
}
?>

This has worked for my testing. but when I have thought of using it for my development job then I faced a trouble. This code does not give the desired result due to the way I need to use it. I need to use it inside function. For a development job and getting all the parent folders, this must go in a function or method. If you use PHP magic constant __FILE__ in function, then it will return the path of the file where it reside and not the path of the file from where it is called. So, for this I need to give some more time. I have found a hack for this. Yes, there was not a direct way of using __FILE__ for this job. And there was no other magic Constant for this. But the solution for getting FileName and Path of the calling page use PHP inbuilt function, so using that solution was not a problem.
The solution for that was using: debug_backtrace().


<?php
$bt = debug_backtrace();
$path = dirname($bt[0]['file']);
?>

So, finally this code will work as expected inside method or function:


<?php
$i = 0;
while($currDirInLoop != 'StopAtThisFolder')
{
    $bt = debug_backtrace();
    $path = dirname($bt[0]['file']);
    if ($i == 0)
        $tmp  = dirname($path);
    else
        $tmp = $path;
    $path = realpath($tmp  . '/../');
    echo '<hr>';
    //var_dump($path);
    echo $currDirInLoop = basename($tmp);
    $i++;
    // fail safe
    if ($i == 10) break;
}
?>

You see lots of debug related data are there. Yes, this is again my testing code and it will be useful for you to modify according to your need of getting parent folders. Code if ($i == 10) break; is only for avoiding infinite loop. StopAtThisFolder is the folder where I want to stop. I do not want to get parents above that.