Tuesday, February 23, 2010

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

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:

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

./bar/bar.php
<?php
echo getcwd(),"\n";
echo dirname(__FILE__),"\n";
?>

You get this output (Windows / Zend Studio Debugger):

C:\Users\me\Zend\workspaces\DefaultWorkspace7\random
C:\Users\me\Zend\workspaces\DefaultWorkspace7\random
-------
C:\Users\me\Zend\workspaces\DefaultWorkspace7\random
C:\Users\me\Zend\workspaces\DefaultWorkspace7\random\bar

On FreeBSD:

# php foo.php
/tmp/tmp
/tmp/tmp
-------
/tmp/tmp
/tmp/tmp/bar

Appearantly, getcwd() returns the CURRENT directory where the file you started executing resided, while dirname(__FILE__) is file-dependant.

Note: for getcwd(), if you put your script in /tmp/test.php, but you started executing that script in / the root directory, getcwd() will return / instead of /tmp

Example:
<?php
echo getcwd();
?>

Running the script from /tmp, returns /tmp
root@host [/tmp] # php test.php
/tmp

While, running the script from /, returns /
root@host [/] # php /tmp/test.php
/

So, please be aware of the difference.

No comments: