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

Viewed 20905

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?

3 Answers

__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__).

Try this.

Move your file into another directory say testing2.

This should be the result.

/home/user/Desktop/testing/
/home/user/Desktop/testing/testing2/

I would think getcwd is used for file operations, where dirname(__FILE__) uses the magic constant __FILE__ and uses the actual file path.


Edit: I was wrong.

Well you can change the working directory, with chdir.

So if you do that...

chdir('something');
echo getcwd()."\n";
echo dirname(__FILE__)."\n";

Those should be different.

Related