Parsing Command Line Arguments 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.

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($argvas$arg){echo"$arg\n";}

Output:

Code:

[asha@home-desktop php]# php test.php anjalitest.phpanjali

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.