Php – Get absolute path of initially run script

includepathPHP

I have searched high and low and get a lot of different solutions and variables containing info to get the absolute path. But they seem to work under some conditions and not under others. Is there one silver bullet way to get the absolute path of the executed script in PHP? For me, the script will run from the command line, but, a solution should function just as well if run within Apache etc.

Clarification: The initially executed script, not necessarily the file where the solution is coded.

Best Answer

__FILE__ constant will give you absolute path to current file.

Update:

The question was changed to ask how to retrieve the initially executed script instead of the currently running script. The only (??) reliable way to do that is to use the debug_backtrace function.

$stack = debug_backtrace();
$firstFrame = $stack[count($stack) - 1];
$initialFile = $firstFrame['file'];