Thursday, April 28, 2011

PHP CLI script and Command line arguments

One of the advantages of  PHP is that, it can be run from the command line like a c program. Sometimes scripts are made to run behind the browser to give faster response to the user, and some time to run the bulky operations. (video conversion, cron, backups).

There are to ways to get the arguments in the script, while running it from command line:



  1. $_SERVER['argv']

    The command itself (i.e. your script filename) and the command line arguments are stored in an array in the $_SERVER variables called 'argv'. It is possible to access the command line arguments from here but it's easier to getopt() because you can then access the arguments by flag and in any order. Running the command "php myscript.php foo bar" and then doing print_r($_SERVER['argv']) would output this:

    Array
    (
        [0] => myscript.php
        [1] => foo
        [2] => bar
    )

  2. getopt()The getopt() function returns the list of command line arguments in an associative array. It returns the arguments passed in based on the parameters passed to it. For example, to get the values for the flags -a -b and -c you would do this:

    $arguments = getopt("a:b:c:");

    If you called the script like this (the first example has spaces between the flag and the value, the second has no spaces but both will return the values):

    php myscript.php -a foo -b bar -c baz
    OR
    php myscript.php -afoo -bbar -cbaz

    Then doing print_r($arguments) would return this:

    Array
    (
        [a] => foo
        [b] => bar
        [c] => baz
    )

    Note that the colons after the value are required; if you don't use them and a flag is passed on the command line with that letter then it won't be returned in the array.
    Another thing to note is that if it one of the values you are looking for is not passed on the command line, then it won't be added to the array return from getopt(). Calling the same $arguments = getopt("a:b:c:") script as in the above example, calling the script like so:

    php myscript.php -a foo

    and then doing print_r($arguments) would show this:

    Array
    (
        [a] => foo
    )

Thanks you.. Hope You like it.

    9 comments: