__FILE__ is a magic constant containing the full path to the executable file. If you are inside an include, its path will contain the contents of __FILE__ .
So, with this setting:
/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 execution, while dirname(__FILE__) depends on the file.
On my web server, getcwd() returns the location of the file that originally started executing. Using the CLI is the same as what you would get if you pwd . This is supported by the SAPI CLI documentation and the comment on the getcwd page:
The CLI SAPI does - contrary to other SAPIs - DO NOT automatically change the current working directory to the one in which the running script is located.
So:
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 With PHP 5.3.0, you can also use the magic constant __DIR__ , which is equivalent to dirname(__FILE__) .
Thom Wiggers Feb 02 2018-10-02 14:56
source share