Search code examples
phpcommand-linecommand-line-interfacepwdworking-directory

How to find the folder from which a PHP command line script was launched?


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?


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.