1

I'm working on some PHP cli tools for MediaWiki and I want to be able to cd into a directory of the wiki, from the shell. Can I do that from PHP? If not, is it possible to wrap the entire thing into something else that is capable of doing this?

For example:

~$ mewsh @coin cd

Should take me the appropriate directory where coinwiki is located. chdir is not sufficient as this will not change the directory after the PHP script is finished.

1

1 Answer 1

1

It's not a matter of whether or not you can do it from php – you can't do it from any spawned process. A spawned process is a new process (created usually with fork and exec). Changes to the working directory of the new process cannot affect the working directory of the parent process.

That said, if you want to get crazy you can: Here's a php script that chdirs to the parent directory and then replaces itself with bash. It can't change the directory of the parent process, but it can start a new shell with a new directory.

<?php
chdir('..'); // Chdir to the parent directory in this php process.
pnctl_exec('/bin/bash'); /* Execute '/bin/bash' in the current process space.
  This is oversimplified in many ways
  – including that I didn't pass any arguments to the shell. */

For further hackery, if you're completely in control of how this script is invoked, you can exec it and replace the current shell with the new one.

~ $ exec php chdir.php
/Users $

But if you intend to share this script with someone you shouldn't have these expectations – it's much saner to manage the working directory only within your own program.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.