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

↘锁芯ラ 提交于 2019-12-17 16:05:08

问题


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?


回答1:


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




回答2:


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.




回答3:


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

cd foo
php bin/test.php

within test.php, getcwd() would return foo (your current working directory) and dirname(__FILE__) would return bin (the dirname of the file executing).



来源:https://stackoverflow.com/questions/2184810/difference-between-getcwd-and-dirname-file-which-should-i-use

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!