I am writing a PHP script and have to get some options (h, n and v). For me, the best way to get it is to use getopt
function. Also, if an unexpected option is passed, I would like to display help message. However, getopt
function only returns expteced options.
Here is my script:
$options = getopt('hnv');
if (!empty($options)) {
foreach (array_keys($options) as $option) {
switch ($option) {
// Run script.
case 'n':
case 'v':
break;
case 'h':
// Display help with OK exit code.
self_usage();
exit(0);
default:
// Display help with ERR exit code.
self_usage('Too many params');
exit(1);
}
}
}
But, if I launch my script with an unexpected option like -p
, it runs, because the options array is empty.
php myscript.php -p
If I pass an unexpected option with an expected one, it runs too.
php myscript.php -pn
php myscript.php -p -n
I've tried to check the passed args count, but this works only if I pass arguments one by one (-n -p
) and not all in one (-np
).
if ((count($argv) - 1) > count($options)) {
self_usage();
}
Is there a good way to check for unexcepted options in all of this case?
Thank you for your help!
The getopt() function is a builtin function in C and is used to parse command line arguments. Syntax: getopt(int argc, char *const argv[], const char *optstring) optstring is simply a list of characters, each representing a single character option.
getopts is a built-in Unix shell command for parsing command-line arguments. It is designed to process command line arguments that follow the POSIX Utility Syntax Guidelines, based on the C interface of getopt. getopts. Developer(s) Various open-source and commercial developers.
RETURN VALUE The getopt() function returns the next option character specified on the command line. A colon (:) is returned if getopt() detects a missing argument and the first character of optstring was a colon (:).
You can try the following:
// remove script called
unset($argv[0]);
$valid_opts = getopt('hnv');
array_walk($argv, function(&$value, $key) {
// get rid of not opts
if(preg_match('/^-.*/', $value)) {
$value = str_replace('-', '', $value);
} else {
$value = '';
}
});
$argv = array_filter($argv);
print_r($argv);
print_r($valid_opts);
print_r(array_diff($argv, array_keys($valid_opts)));
array_diff
will give you the opts that are in the array that are not valid.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With