Handling Command Line Arguments in PHP

When working with PHP in an web environment programmers are often used to the comfort of having the associative arrays $_GET and $_POST to hold the data to be passed on as arguments. During command line runtime however, there is only a numerated array called $argv holding each argument:

The following code makes use of that variable:

<?php print_r($argv); ?>

Running it at the command line with appended arguments:

$ php5 test.php argument1 argument2

The dumped array of arguments:

Array
(
    [0] => test.php
    [1] => argument1
    [2] => argument2
)

For one of my projects that was supposed to be run at the command line I wanted an easier way to keep track of command line arguments. I put together a function that parsed the simple numerated array into an associated one:

Parsing the command line arguments (highlighted version)

<?php
function arguments($argv) {
    $_ARG = array();
    foreach ($argv as $arg) {
        if (ereg('--[a-zA-Z0-9]*=.*',$arg)) {
            $str = split("=",$arg); $arg = '';
            $key = ereg_replace("--",'',$str[0]);
            for ( $i = 1; $i < count($str); $i++ ) {
                $arg .= $str[$i];
            }
                        $_ARG[$key] = $arg;
        } elseif(ereg('-[a-zA-Z0-9]',$arg)) {
            $arg = ereg_replace("-",'',$arg);
            $_ARG[$arg] = true;
        }
    
    }
return $_ARG;
}
 
print_r(arguments($argv));
?>

This version would treat the following arguments more nicely

$ php test.php --argument1=value1 -flag1 --argument2=value2 -flag2

The dumped associative array generated by the above code:

Array
(
    [argument1] => value1
    [flag1] => 1
    [argument2] => value2
    [flag2] => 1
)

For an example of how this can be used in a real application I suggest you take a closer look at my rewritten Youtube ripper.

One Response to “Handling Command Line Arguments in PHP”

  1. Liesbeth Kiki Says:

    that’s why it will never wor. Liesbeth Kiki.

Leave a Reply