Writing a PHP command line script that takes options

First of all, we make our file start like this.

#!/usr/bin/env php

This allows us to run the script without prefixing it with the “php” command, and instead we can run it like this:

chmod +x myscript  # This gives execution permissions to the script, do it only once
./myscript --first=option --second --third=option

If we want our script to take options like in the example above, we can use this snippet:

$options = array();
 
foreach ($argv as $arg){
	preg_match('/\-\-(\w*)\=?(.+)?/', $arg, $value);
	if ($value && isset($value[1]) && $value[1]) 
		$options[$value[1]] = isset($value[2]) ? $value[2] : null;
}

The $options array will hold the supplied options. You can then use them like this:

if (!isset($options['somevalue']))
	// show an error
 
if (isset($options['dosomething']))
	// do something
  1. If you want to check against arguments without a value (i.e. –help) isset() will not work, you will need to use array_key_exists() as per the second example at http://uk2.php.net/manual/en/function.isset.php

    This is due to the default value of an empty argument being set to NULL

  2. Maybe you should have provided the link to the manual where it details php’s command line interface -> http://pt.php.net/features.commandline

    Nice post. I have made one or two scripts for the cli but very basic.

  3. $argv[0] is always the filename so anything after the .php is your options

    • Guillermo Rauch about 1 year ago

      Right, but $argv is basically a explode(‘ ‘, $command). If you had read the code you’d know we’re parsing options preceded by — that can optionally include a value.

      $argv[1] in this case would only get you –something=something.