Question

Let's say I have the following folder structure on my hard-drive:

/some/dir/
    .
    scripts/
        myfile.php

Then from '/some/dir/', I run the following command:

/some/dir/$ php scripts/myfile.php

Then, in PHP, how can I find the folder from which the command was launched (i.e. '/some/dir')?

I've tried with getcwd() and shell_exec('pwd') but they both only return the path of the PHP script (i.e. /some/dir/scripts). Any idea how to do this?

Was it helpful?

Solution

You can refer, for example, to $_SERVER['PWD'] and $_SERVER['OLDPWD']

For example, I have script test.php in ./dev subfolder with contents:

var_dump($_SERVER['PWD'], $_SERVER['OLDPWD']);

So, you can see:

user@host:/var/www/data$ php dev/test.php       
string(13) "/var/www/data"
string(17) "/var/www/data/dev"

So, first one is what you're looking for.

Script full name, as usual, will be available in __FILE__ constant.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top