Search code examples
phpgetopt

Catch unexpected options with 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!


Solution

  • 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.