0

In a PHP cli script I'm writing I need to change the path for the user that's running the script. The destination path is not fixed.

The script will be used on machines running on Ubuntu. With a bash script I could use sourcing, but that doesn't seem to work with PHP scripts. When I try that, the hashbang referring to the php binary at the top of the script is ignored and the script interpreted as a bash script. I don't really know what else to try.

Is there some way to achieve this?

7
  • 1
    php.net/chdir Commented Jul 31, 2015 at 15:48
  • @Farkie I don't think that's relevant here - you cannot use chdir (or any other function for that matter) to modify the parent shell. Commented Jul 31, 2015 at 15:50
  • Oh, you can't modify the parent shell.. You could technically spawn another bash shell whilst inside php after changing dir.. chdir('..'); pnctl_exec('/bin/bash'); Commented Jul 31, 2015 at 15:53
  • You can't directly modify the parent's current directory from a child process. Would it be possible to wrap the child PHP process ... for example, have the PHP script generate a sourceable bash file? Commented Aug 1, 2015 at 18:34
  • @Beel Hmm, as in make a bash script that runs the PHP script, which in turn writes a sourceable file at a predestined location, and when it returns the original bash script sources it? I think you may have just found a solution. :) Commented Aug 1, 2015 at 20:08

1 Answer 1

1

As I understand the problem, you have a parent process that will launch PHP in a child process to execute a PHP script. And you want the logic of that PHP script to cause the parent process' working directory to change. The PHP script cannot directly modify the parent's working directory. But ... you can have the child PHP script create a new file that contains a cd newpath command, then source that newly created file. So

Some main.sh script file contains something like:

/bin/php /path/to/the/php/script.php
source /tmp/generatedscript
rm /tmp/generatedscript

script.php should create a new tmp file that contains only a cd command with the desired directory as target. main.sh can source that file, and you are now in a new wd.

Be sure to source the main.sh so that the commands all run within the current process.

Sign up to request clarification or add additional context in comments.

1 Comment

If you were going to do that you might as well use eval instead of a tempfile — eval `php whatever.php`

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.