Link to home
Start Free TrialLog in
Avatar of DrDamnit
DrDamnitFlag for United States of America

asked on

Most elegant way to check command line args in PHP

I am writing a PHP script that will use a lot of parameters. While I know how to check them and work with them, I am looking for an ELEGANT way to work with the parameters that emulates how most Linux applications and packages work. So, here are the requirements:

1. Minimal, efficient and elegant code
2. Paramters may be issued in ANY order. (Example: command --first --second --third or command --third --first --second)
3. Code must be re-usable for different scripts.
ASKER CERTIFIED SOLUTION
Avatar of gr8gonzo
gr8gonzo
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of DrDamnit

ASKER

I think I am in love.

Question: how do I check (most succinctly) that all the required variables are there? I have looked at the docs, and tried code similar to what's below...

if(!(getopt))
    print_help();

Open in new window



I don't want to have to tell it
if(isset($opt['requiredvar1']) && isset($opt['requiredvar2']))
     do_something_userful();

Open in new window

Here's my other problem:

I want it to behave like a normal command line program. So, temp.php -a -b -c would tell it to do three things, just by their very presence in the command line. I don't necessarily want to have to specify -a true -b true -c true. But when I try it, this is what I get:

michael@michael-desktop:~/php/infusion/includes$ php temp.php -a -b -c -d
array(2) {
  ["a"]=>
  string(2) "-b"
  ["c"]=>
  string(2) "-d"
}

Open in new window


Thoughts?
FYI... here's the test code:
<?php
$shortopt = "a:b:c:d::";
$opt = getopt($shortopt);
var_dump($opt);
if(!$opt)
{
        print_help();
        exit(1);
}
function print_help()
{
?>
        Help screen

        -a      Test arg (required)
        -b      Test arg (required)
        -c      Test arg (requried)
        -d      Test arg (optional)
<?php
}
?>

Open in new window

So there's three formats that simply specifies how PHP will treat the command line arguments:

option (no colons) - This is just for true/false flags, like -a -b -c. PHP won't look ahead for another value.

option + 1 colon - This is for options with values like -a foo -b bar, so PHP will look after the option for the value. One colon means the value is required.

option + 2 colons - Same as 1 colon except it's optional.

So if you wanted to do php temp.php -a -b -c -d, then you'd want getopt("abcd").

If you want to further validate that certain options are required, then you need to simply process the results of the getopt() call.