PHP:如何将当前工作目录设置为与执行脚本的目录相同
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5254000/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP: How to set current working directory to be same as directory executing the script
提问by MF86
I'm in the process of transferring my website from one server to another. I have some php scripts that use the is_readable function which uses the current working directory.
我正在将我的网站从一台服务器转移到另一台服务器。我有一些使用 is_readable 函数的 php 脚本,该函数使用当前工作目录。
On the old server, when I call getcwd(), it outputs the folder in which the script is being executed. On the new server it outputs the root directory '/'.
在旧服务器上,当我调用 getcwd() 时,它会输出正在执行脚本的文件夹。在新服务器上,它输出根目录“/”。
I would like to know how I can configure PHP to use the current folder instead of '/'. I don't want to have to change any PHP code that already works on the old server. I can configure the new server, but don't know what settings to change.I'm using apache2, if that helps.
我想知道如何配置 PHP 以使用当前文件夹而不是“/”。 我不想更改任何已经在旧服务器上运行的 PHP 代码。我可以配置新服务器,但不知道要更改哪些设置。如果有帮助,我正在使用 apache2。
EDIT: It seems as though my working directory is not root like I thought. When I create a testFile.php and echo getcwd() it shows the directory the php file is in. But in my problem file, in the same directory, getcwd() shows up as '/'
编辑:似乎我的工作目录不像我想象的那样是根目录。当我创建一个 testFile.php 并 echo getcwd() 时,它显示了 php 文件所在的目录。但在我的问题文件中,在同一目录中,getcwd() 显示为“/”
回答by Czechnology
chdir(__DIR__);
chdir(__DIR__);
or
或者
chdir(dirname(__FILE__));
chdir(dirname(__FILE__));
(see chdirand magic constants).
But that should be by default.
但这应该是默认的。
回答by Pekka
回答by alex
You can get the current directory a script is in with dirname(__FILE__)
or __DIR__
if >= PHP 5.3.
您可以获取脚本所在的当前目录,dirname(__FILE__)
或者__DIR__
如果 >= PHP 5.3。