CHAPTER 16 - Parsing Command-Line Options

Computer Education, Training & Tutorial Resources - ComputerEducationWorld.com
Home » Free Computer Books » PHP » PHP 5 Power Programming »

Command-line options are used in UNIX to specify alternate behavior or addi-
tional parameters for commands. You spot them by the leading dash. Here are
some examples:
$ ls ­ltr
$ rm ­f junk
Usually, options are located before regular parameters (that do not start
with a dash) on the command line. Some commands, such as cvs or pear, have
additional subcommands accepting their own set of options. The PEAR
installer is one such command.
There is no getopt function built into PHP, but PEAR offers a package
called Console_Getopt that supports both short and long (GNU-style) options.
Console_Getopt is bundled with PHP and is installed by default unless you
explicitly disable PEAR.
Here is a command-line script accepting four short options: -v and ­q and
increasing or decreasing verbosity level, -h for displaying help, or ­c for setting
another configuration file:
#!/usr/bin/php
<?php
require_once “Console/Getopt.php”;
$verbose = 1;
$config_file = $_ENV[’HOME’] . ‘/.myrc’;
$options = Console_Getopt::getopt($argv, ‘hqvc:’);
foreach ($options[0] as $opt) {
switch ($opt[0]) {
case ‘q’:
$verbose–;
break;
case ‘v’:
$verbose++;
break;
case ‘h’:
usage();
exit;
case ‘c’:
$config_file = $opt[1];
break;
}
}
if ($verbose > 1) {
print “Config file is \”$config_file\”.\n”;
}
// rest of the script code goes here
function usage() {
$stderr = fopen(”php://stderr”, “w”);
$progname = basename($GLOBALS[’argv’][0]);
fwrite($stderr, “Usage: $progname [-qvh] [-c config-file]
Options:
-q be less verbose
-v be more verbose
-h display help
-c <file> read configuration from <file>
“);
fclose($stderr);
}
?>
First, the script includes the Console_Getopt class definition. After setting
default values for $verbose and $config_file, the getopt() call is accomplished
with the parameter list and a string specifying which options are accepted.
Take a look at the option specification string. Each alphanumeric charac-
ter in the option specification string is a valid option. If the option character is
followed by a colon, the option is expected to have a value. In the previous
example, c: says that the ­c option expects a parameter, which is the configu-
ration file to use. The ­q, -v, and ­h options don’t have any following special
characters, so they are simple flag/toggle-type options.
The getopt() method returns an array of the form array(array(option,
value), …). The foreach loop iterates through this array, and $opt is assigned
to the array(option, value). For flag options, the value will always be NULL (no
need to check because you already know which options are plain flags), while
for options taking parameters, the second element in this array is the actual parameter. For example, -c foo would give array(’c', ‘foo’) in $foo. It is pos-
sible to treat the same option as many times as needed. In this example, the
verbosity level of the program increases by 1 each time the ­v option is used. If
the user specifies -vvvvv to it, the verbosity level will be increased 5 times.
It is also possible to specify that an option parameter is optional by using
two colons instead of one–for example, c::. When encountering an option
parameter that is not mandatory, Console_Getopt uses the remains of the
option as the option parameter value. For example, if the ­c option was speci-
fied with c::, the option string -cfoo.cf would give the option parameter value
foo.cf, but just -c would be allowed, too. However, when an option parameter
becomes optional, -c foo is no longer allowed; it has to be -cfoo.
Following is the same example supporting both short- and long-style
options:
#!/usr/bin/php
<?php
require_once “Console/Getopt.php”;
$verbose = 1;
$config_file = $_ENV[’HOME’] . ‘/.myrc’;
$options = Console_Getopt::getopt($argv, ‘hqvc::’,
array(’help’, ‘quiet’, ‘verbose’,
‘config=’));
foreach ($options[0] as $opt) {
var_dump($opt);
switch ($opt[0]) {
case ‘q’: case ‘–quiet’:
$verbose–;
break;
case ‘v’: case ‘–verbose’:
$verbose++;
break;
case ‘h’: case ‘–help’:
usage();
exit;
case ‘c’: case ‘–config’:
$config_file = $opt[1];
break;
}
}
if ($verbose > 1) {
print “Config file is \”$config_file\”.\n”;
}
// rest of the script code goes here
function usage() {
$stderr = fopen(”php://stderr”, “w”);
$progname = basename($GLOBALS[’argv’][0]);
fwrite($stderr, “Usage: $progname [options]
Options:
-q, –quiet be less verbose
-v, –verbose be more verbose
-h, –help display help
-c <file>, –config=<file> read configuration from <file>
“);
fclose($stderr);
}
?>

Good Practices
When writing shell scripts, you should follow some good practices to make life
easier for yourself and others who will use your script.
For example, most UNIX users expect their programs to respond to foo ­h
or foo –help with a brief usage message, or that they print errors on standard
error instead of standard output. This section lists some practices that the
authors consider GoodTM.

Usage Message
After using UNIX/Linux for a while, you get used to
being able to type command ­help or command ­h for a brief description of a com-
mand’s option and general usage. Most UNIX users expect their program to
respond to these options.
Display a usage message on standard error and exit with a non-0 code if
the script is started without the expected parameters, or if it runs with the -h
option (–help if you are using long options). The usage message should list all
the required and optional parameters, and could look something like this:
Usage: myscript [options] <file…>
Options:
-v, –version Show myscript version
-h, –help Display this help text
-d dsn, –dsn=dsn Connect to database “dsn”
There is a standard notation for options and parameters as well:
[-c] May have ­c.
{-c foo} Must have ­c with a parameter.
[-abcdef] May have any of ­a … ­f.
[-a | -b] May have either ­a or ­b.
{-a | -b} Must have either ­a or ­b.
<file> Must have file as a parameter (not option).
<file…> Must have 1+ file parameters.
[file…] May have 1+ file parameters.

If your program accepts only a few options, you should list them on the
first line of the usage message, like this:
Usage: myscript [-vh] [-d dsn] <file…>
Options:
-v, –version Show myscript version
-h, –help Display this help text
-d dsn, –dsn=dsn Connect to database “dsn”


• • •
 



captcha PHP Script Free PHP captcha script free php
Website Design by WebWalas.com