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.
This is what I use and it works in Linux environments. I don't think this would work on a Windows machine...
it gives you current script(the script inside which you placed this code) directory without trailing slash. this is important if you want to include other files with the result
If you're looking for the absolute path relative to the server root, I've found that this works well:
Just use below :
Examples for:
https://(www.)example.com/subFolder/yourfile.php?var=blabla#555
The easiest way to retrieve the absolute path of the initially executed script from that "main" script and any script included with
include
,require
,require_once
is by storing it in a constant at the beginning of the main script:__FILE__
returns the path of the current script. Used inside an included script returns the path of the included file, not the script initially run as the OP asks:The solution of storing the
__FILE__
into a constant is easier and faster than retrieving the path usingdebug_backtrace()
The solution above is suitable when there is a single "main" script that
include
s every other needed script, as in most web applications.If that's not the case and there may be several "intital scripts" then to avoid redefinitions and to have the correct path stored inside the constant each script may begin with: