PHP Command-Line PHP
Parsing Program Arguments
Problem
You want to process arguments passed on the command line.
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.";
Discussion
Example Parsing commmand-line arguments
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.
The $argc and $argv variables are concise, but they are not populated if the register_argc_argv config directive is turned off. However, $_SERVER['argc'] and $_SERVER['argv'] always contain the argument count and argument values. Those are good places to look for argument information if you want maximally portable code.
No comments:
Post a Comment