I have a PHP script in some directory. When I call it from the command line, getcwd(), __DIR__
and exec("pwd") return the directory of the script itself, not pwd.
E.g. calling /some/place/test.php from /tmp:
echo(getcwd()); // prints /some/place
echo(exec("pwd")); // prints /some/place
echo(__DIR__); // prints /some/place
echo($_SERVER["PWD"]); // prints /tmp
$_SERVER["PWD"] has the value that I need, but it's not mentioned in docs http://php.net/manual/en/reserved.variables.server.php
Almost hit the "Post question" and guessed to check command line parameters. :-)
$ php -h
...
-C Do not chdir to the script's directory
...
For me, the solution was to use getcwd().
The results I got from my tests where differents from yours.
About $_SERVER['PWD']:
As they explain in Undefined index 'PWD' in $_server, it is dangerous to use it.
As you said, it's not present in the documentation and it's not guaranteed that it's working as expected.
About getcwd():
This is the test I've done. Please consider that testGetCwd.php
contains only a echo getcwd();
.
// working dir: /home/me
// phpfile dir: /var/www/phpfiles
cd /home/me
php /var/www/phpfiles/testGetCwd.php
// echo /home/me
Note:
- Be careful if you are using chdir
because is going to change the current working directory.
- It seems there is a change in functionality from PHP 4
to PHP 5
All the above points may explain the behaviour you were experiencing.