Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catch unexpected options with getopt

Tags:

php

getopt

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!

like image 417
Devatoria Avatar asked Aug 19 '14 16:08

Devatoria


People also ask

What is getopt used for?

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.

What is getopt in shell?

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.

What does getopt return?

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 (:).


1 Answers

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_diffwill give you the opts that are in the array that are not valid.

like image 189
Eduardo Romero Avatar answered Sep 24 '22 15:09

Eduardo Romero