Recipe 25.1. Parsing Program Arguments


25.1.1. Problem

You want to process arguments passed on the command line.

25.1.2. Solution

Look in $argc for the number of arguments and $argv for their values. The first argument, $argv[0], is the name of script that is being run:

if ($argc != 2) {     die("Wrong number of arguments: I expect only 1."); } $size = filesize($argv[1]); print "I am $argv[0] and report that the size of "; print "$argv[1] is $size bytes.";

25.1.3. Discussion

In order to set options based on flags passed from the command line, loop through $argv from 1 to $argc, as shown in Example 25-1.

Parsing commmand-line arguments

<?php for ($i = 1; $i < $argc; $i++) {     switch ($argv[$i]) {     case '-v':         // set a flag         $verbose = true;         break;     case '-c':         // advance to the next argument         $i++;         // if it's set, save the value         if (isset($argv[$i])) {             $config_file = $argv[$i];         } else {             // quit if no filename specified             die("Must specify a filename after -c");         }         break;     case '-q':         $quiet = true;         break;     default:         die('Unknown argument: '.$argv[$i]);         break;     } } ?>

In this example, the -v and -q arguments are flags that set $verbose and $quiet, but the -c argument is expected to be followed by a string. This string is assigned to $config_file.

25.1.4. See Also

25.2 for more parsing arguments with getopt; documentation on $argc and $argv at http://www.php.net/reserved.variables.




PHP Cookbook, 2nd Edition
PHP Cookbook: Solutions and Examples for PHP Programmers
ISBN: 0596101015
EAN: 2147483647
Year: 2006
Pages: 445

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net