__FILE__
is a 魔法常数 http://php.net/manual/en/language.constants.predefined.php包含您正在执行的文件的完整路径。如果您位于包含文件内,则其路径将是以下内容__FILE__
.
所以通过这个设置:
/文件夹/随机/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";
你得到这个输出:
/folder/random
/folder/random
-------
/folder/random
/folder/random/bar
So getcwd()
返回您开始执行的目录,同时dirname(__FILE__)
是文件相关的。
在我的网络服务器上,getcwd()
返回最初开始执行的文件的位置。使用 CLI 它等于执行后得到的结果pwd
。这是由CLI SAPI 文档 https://secure.php.net/manual/en/features.commandline.differences.php以及评论getcwd
手册页:
CLI SAPI 与其他 SAPI 不同,不会自动将当前工作目录更改为启动脚本所在的目录。
所以就像:
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
当然,另请参阅手册:http://php.net/manual/en/function.getcwd.php http://php.net/manual/en/function.getcwd.php
UPDATE:从 PHP 5.3.0 开始你还可以使用魔法常量__DIR__
这相当于dirname(__FILE__)
.