What is the best way to use absolute paths in PHP?
I have always used relative paths in PHP. Last time I have realized that there were something like absolute paths.
But what is the best way to use them?
getenv("DOCUMENT_ROOT"); ?
dirname(__FILE__); ?
How do you deal with the implementation? Pl开发者_开发知识库ease give some ideas.
When I want to use files that are "relative" to the one in which I am writing some code, I'm always using :
dirname(__FILE__)
This allows me to :
- have absolute paths that'll work everywhere, no matter to which server I deploy my application
- still use path that "look like" relative ones when I'm writting them.
For instance, to include a file that's in a "classes" sub-diretory, I would generally use :
require dirname(__FILE__) . '/classes/MyClass.php';
Note that this will work even if you're executing your script from the command-line -- while a solution based on some kind of DocumentRoot will probably not work when not using a web-server.
And, with PHP >= 5.3, you can also use the __DIR__
magic constant, which has exactly the same value as dirname(__FILE__)
, but is evaluated at compile-time, and not execution-time -- which is a bit better for performances.
I have always used dirname(__FILE__)
, it works perfectly for what I need it to. I store it in a variable at the beginning of script execution which is carried along with any global data I use, then when I require or include new files I can easily include it into my paths without too much problem.
I've always used $_SERVER['DOCUMENT_ROT'] or $_SERVER['PHP_SELF']
I donno, to everyone their own I suppose
精彩评论