Parsing Command Line Arguments in PHP

Discussion in 'PHP' started by asha, Oct 8, 2012.

  1. asha

    asha New Member

    Joined:
    Nov 9, 2006
    Messages:
    44
    Likes Received:
    2
    Trophy Points:
    0
    Occupation:
    Homemaker
    Location:
    Kolkata
    Home Page:
    http://whatanindianrecipe.com
    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 [THREAD=21746]Command Line Arguments[/THREAD], [THREAD=29146]Reading Command Line Arguments in Python[/THREAD].

    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,

    PHP:
    foreach ($argv as $arg) {
        echo 
    "$arg\n";
    }
    Output:
    Code:
    [asha@home-desktop php]# php test.php anjali
    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.

    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);

    var_dump($options);
    As you can see, the configuration is easy and understandable, and so it the parsed array.
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice