Difference Between getcwd() and dirname(__FILE__) ? Which should I use?

__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

<?php
echo getcwd() . "\n";
echo dirname(__FILE__) . "\n" ;
echo "-------\n";
include 'bar/bar.php';

/folder/random/bar/bar.php

<?php
echo getcwd() . "\n";
echo dirname(__FILE__) . "\n";

You get this output:

/folder/random
/folder/random
-------
/folder/random
/folder/random/bar

So getcwd() returns the directory where you started executing, while dirname(__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 executed pwd. This is supported by the documentation of the CLI SAPI and a comment on the getcwd manual page:

the CLI SAPI does – contrary to other SAPIs – NOT automatically change the current working directory to the one the started script resides in.

So like:

thom@griffin /home/thom $ echo "<?php echo getcwd() . '\n' ?>" >> test.php
thom@griffin /home/thom $ php test.php 
/home/thom
thom@griffin /home/thom $ cd ..
thom@griffin /home $ php thom/test.php 
/home

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 to dirname(__FILE__).

Leave a Comment