In PHP what is the difference between
getcwd()
dirname(__FILE__)
They both return the same result when I echo from CLI
echo getcwd()."\n";
echo dirname(__FILE__)."\n";
Returns:
/home/user/Desktop/testing/
/home/user/Desktop/testing/
Which is the best one to use? Does it matter? What to the more advanced PHP developers prefer?
__FILE__is a magic constant containing the full path to the file you are executing. If you are inside an include, its path will be the contents of__FILE__.So with this setup:
/folder/random/foo.php
/folder/random/bar/bar.php
You get this output:
So
getcwd()returns the directory where you started executing, whiledirname(__FILE__)is file-dependent.On my webserver,
getcwd()returns the location of the file that originally started executing. Using the CLI it is equal to what you would get if you executedpwd. This is supported by the documentation of the CLI SAPI and a comment on thegetcwdmanual page:So like:
Of course, see also the manual at http://php.net/manual/en/function.getcwd.php
UPDATE: Since PHP 5.3.0 you can also use the magic constant
__DIR__which is equivalent todirname(__FILE__).