PHP has the getopt() function for getting options or command line arguments from a CLI PHP script. This provides a simple way to get values from the command line like e.g. “-a foo”. This post looks at how to do this. More details can be found in the PHP getopt() manual page.
The command itself (i.e. your script filename) and the command line arguments are stored in an array in the $_SERVER variables called ‘argv’. It is possible to access the command line arguments from here but it’s easier to getopt() because you can then access the arguments by flag and in any order. Running the command “php myscript.php foo bar” and then doing print_r($_SERVER[‘argv’]) would output this:
Array (  => myscript.php  => foo  => bar )
The getopt() function returns the list of command line arguments in an associative array. It returns the arguments passed in based on the parameters passed to it. For example, to get the values for the flags -a -b and -c you would do this:
$arguments = getopt("a:b:c:");
If you called the script like this (the first example has spaces between the flag and the value, the second has no spaces but both will return the values):
php myscript.php -a foo -b bar -c baz OR php myscript.php -afoo -bbar -cbaz
Then doing print_r($arguments) would return this:
Array ( [a] => foo [b] => bar [c] => baz )
Note that the colons after the value are required; if you don’t use them and a flag is passed on the command line with that letter then it won’t be returned in the array.
Another thing to note is that if it one of the values you are looking for is not passed on the command line, then it won’t be added to the array return from getopt(). Calling the same $arguments = getopt(“a:b:c:”) script as in the above example, calling the script like so:
php myscript.php -a foo
and then doing print_r($arguments) would show this:
Array ( [a] => foo )
Version used for this post
The version I used for testing with this post was PHP 5.1.6 on CentOS 5.0. According to the PHP manual page for getopt() on versions of PHP prior to 5.3 did not work. There is also an “optional” parameters option from 5.3 which doesn’t work as expected in the version 5.1.6 that I used, and a second parameter to the getopt() function for long options (in the style –name=value or –name value) which is not widely available prior to 5.3. On the CentOS system I was using, attempting to use the second paameter for long options resulted in this error message:
PHP Warning: getopt(): No support for long options in this build in ...
Therefore if you are targeting systems with PHP installations prior to 5.3 you are best to stick with the short options only.