I have two PHP scripts for command line use:
- standalone.php: a standalone script using the native getopt() function.
- shell-loop.php: a shell-like interface that repeatedly reads a line, exits if necessary, otherwise passes the input with some additions defined in this 'shell'-environment to the standalone script called through inclusion
As the standalone script uses getopt() I would like to change the argument list it parses in the shell-loop script right before inclusion. I have tried setting $argv and $_SERVER['argv'] (argc respectively) to the new values but it seems getopt() does not read those variables, but - so I assume - it accesses the arguments passed to php directly. (Unless I made some silly mistake..)
So my question would be: can the argument list used by getopt() easily be altered from within a php script and how so? If not, for curiosity's sake, I would also wonder if there is a dirty way to do it?
shell-loop.php:
do {
echo "> ";
$cmd = trim(fgets(STDIN));
if (in_array($cmd,array('exit','bye')))
{
break;
}
$argv = explode(' ',$cmd);
// .. add some options here
array_unshift($argv,'--option1');
array_unshift($argv,'--option2');
// ...
$argc = count($argv);
$_SERVER['argv'] = $argv;
$_SERVER['argc'] = $argc;
// standalone.php relies on getopt() to get any optional parameters
include __DIR__ . '/standalone.php';
} while(true);
and var_dump($GLOBALS) before the include (with actual arguments):
array(10) {
["GLOBALS"]=>
*RECURSION*
["argv"]=>
array(5) {
[0]=>
string(6) "bt.php" <- inserted option
[1]=>
string(4) "--nl" <- inserted option
[2]=>
string(1) "-" <- inserted option
[3]=>
string(2) "on"
[4]=>
string(2) "A1"
}
["argc"]=>
&int(5)
.. GET POST etc here ..
["_SERVER"]=>
array(30) {
.. many things here ..
["argv"]=>
array(5) {
[0]=>
string(6) "bt.php" <- inserted option
[1]=>
string(4) "--nl" <- inserted option
[2]=>
string(1) "-" <- inserted option
[3]=>
string(2) "on"
[4]=>
string(2) "A1"
}
["argc"]=>
int(5)
}
}
The third-party getopt class as referenced here would do the job, yes.
I'll look up php's getopt implementation when I get the time, but thought it might be interesting to have the question answered here..
Structurally this approach makes sense in my case, but yes I could do it differently.