Parsing Command Line Arguments in PHP

asha's Avatar author of Parsing Command Line Arguments in PHP
This is an article on Parsing Command Line Arguments in PHP in PHP.
Most of us have know PHP as a language used for web development, but it is also being used for writing backend processing scripts, backup scripts, deferred processing scripts etc. for a long time but still not as much as other scripting languages as Perl, Python, or Ruby. But if you are a PHP developer, why not use your PHP knowledge to write scripts for which you otherwise would have use another language.

Here we would be looking at how to read command line arguments in a PHP script, you can refer to these articles for more knowledge about command line arguments Command Line Arguments, Reading Command Line Arguments in Python.

The Basics

The PHP interpreter automatically collects the command line arguments passed by the user via the shell, and stores it in a special array variable $argv, these contain the arguments in the order they were passed, the first one always being the command/script filename executed.

Follow the example below,

Code: PHP
foreach ($argv as $arg) {
    echo "$arg\n";

[asha@home-desktop php]# php test.php anjali

Advanced Command Line Parsing

Now, let us look at how to parse command line arguments as the professional programs do, where order of the options do no matter, arguments can be passed in name-value pairs. For this purpose we'll be using a PEAR package Console_GetoptPlus, it is really customizable and easy to use. Follow the code below, which is quite self-explanatory.

Code: PHP
require_once 'Console/GetoptPlus.php';

$config = array(
    'header' => array('Test Program'),
    'options' => array(
        array('long' => 'name', 'short' => 'n', 'type' => 'mandatory', 'desc' => array('Your name')),
        array('long' => 'debug', 'short' => 'd', 'type' => 'noarg', 'desc' => array('Debug flag'))

$options = Console_Getoptplus::getoptplus($config);


As you can see, the configuration is easy and understandable, and so it the parsed array.