Difference between getcwd () and dirname (__ FILE__)? What should i use?

In PHP, what's the difference between

getcwd() dirname(__FILE__) 

Both of them return the same result when I echo from the CLI

 echo getcwd()."\n"; echo dirname(__FILE__)."\n"; 

Return:

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

Which one is best to use? Does it matter? What do more advanced PHP developers prefer?

+21
directory php
02 Feb '10 at 14:40
source share
3 answers

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

+46
Feb 02 2018-10-02
source share

Try it.

Move the file to another directory, say testing2 .

This should be the result.

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

I would think getcwd 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 this ...

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

Those should be different.

+1
Feb 02 2018-10-02
source share

If you call the file from the command line, the difference becomes clear.

 cd foo php bin/test.php 

inside test.php, getcwd() will return foo (your current working directory) and dirname(__FILE__) will return bin (the name of the executable file).

+1
Dec 18 '15 at 10:08
source share



All Articles