As long as the arguments you want to pass to your script do
not start with the - character, there's nothing special to
watch out for. Passing an argument to your script which starts
with a - will cause trouble because PHP itself thinks it has
to handle it. To prevent this, use the argument list separator
--. After this separator has been parsed by PHP, every argument
following it is passed untouched to your script.
# This will not execute the given code but will show the
PHP usage
$ php -r 'var_dump($argv);' -h
Usage: php [options] [-f] <file> [args...]
[...]
# This will pass the '-h' argument to your script and prevent
PHP from showing it's usage
$ php -r 'var_dump($argv);' -- -h
array(2) {
[0]=>
string(1) "-"
[1]=>
string(2) "-h"
}
However, there's another way of using PHP for shell scripting.
You can write a script where the first line starts with
#!/usr/bin/php. Following this you can place normal PHP
code included within the PHP starting and end tags. Once
you have set the execution attributes of the file appropriately
(e.g. chmod +x test) your script can be executed like a
normal shell or perl script: #!/usr/bin/php
<?php
var_dump($argv);
?>
Assuming this file is named test in the current directory,
we can now do the following: $ chmod 755 test
$ ./test -h -- foo
array(4) {
[0]=>
string(6) "./test"
[1]=>
string(2) "-h"
[2]=>
string(2) "--"
[3]=>
string(3) "foo"
}
As you see, in this case no care needs to be taken when
passing parameters which start with - to your script.
Long options are available since PHP 4.3.3.
|