• home
  • forum
  • my
  • kt
  • download
  • Introducing the PHP Command Line Interface

    Author: 2008-08-27 08:06:52 From:

    In this short article I will introduce you to the PHP Command Line Interface (or CLI for short). PHP CLI allows you to run PHP scripts directly from the command line bypassing the need for a web server.

    Note: This article assumes that you are using PHP v4.3.0 or higher.

    Why is it useful?

    The PHP CLI can be useful for writing scripts that you want to run in the background or via cronjobs such as backups, pruning log files or running programs. PHP CLI scripts are also useful for testing small chunks of code without having to upload it to your web server first.

    Handling Input and Output

    In most scripts you will want to get some input from the user such as asking them to select an option and send some output back to them such as displaying the results

    Outputting information to the screen is essentially the same as when using a web server. Using echo and print are the recommended ways to send output.

    PHP Code:
    <?php
     
    echo "Look!  I'm some output!n";
    print 
    'So am I!';
    This will result in:

    Code:
    Look!  I'm some output!
    So am I!
    There are two important differences between using PHP on the command line and using PHP in a web browser to note in the above script. The first is that we don't use <br /> as we normally would to make a new line. Instead we use the new line character n. The second difference is that when using the new line character n, you must enclose the string in double-quotes. Like variables, PHP won't parse the n if it is enclosed in single-quotes, it will just echo it as normal text.

    As with most scripts, you will eventually wish to get some input from the user. The PHP CLI provides a few ways to do this. The most common is to use the fgets() function. fgets() will read everything the user types until they press Enter.

    PHP Code:
    <?php
     
    echo 'Please enter your first name: ';
    $firstName fgets(STDIN);
     
    echo 
    'Hello ' $firstName;
    As you can see in the above script, it asks the user to enter their name. fgets() then waits for the user to press Enter, then puts their input into the $firstName variable. We then use this in our personal greeting.

    Note: STDIN and STDERR

    STDIN and STDOUT are special streams provided by PHP for Input and Output. STDIN (STandarD INput) will contain all input from the user and STDOUT (STandarD OUTput) will contain all output that gets sent to the user.

    So using fgets(STDIN) means that we want to fetch input from the Standard Input stream using the fgets() function.

    There are many other functions for fetching user input such as fgetc and sscanf which are worth investigating further


    Parsing parameters / arguments to your CLI script

    You will frequently find yourself needing to parse command line arguments to your CLI scripts.

    In a web-based application you would typically do this by adding them to the URL:

    http://www.example.com/myscript.php?...something=else

    This would result in the following variables becoming available in your PHP script:

    PHP Code:
    $_GET['this'// Contains "that"
    $_GET['something'// Contains "else" 
    Arguments are handled slightly differently in a PHP CLI script. To pass arguments in your CLI script you would do the following:

    Code:
    php myscript.php something else
    This would pass the values "something" and "else" to your PHP script.

    To use these within your script you need to take advantage of the $_SERVER superglobal array. Specifically, $_SERVER['argc'] and $_SERVER['argv'].

    $_SERVER['argc'] (argument count) contains the number of arguments passed to your script. It's important to note that this number includes the name of the script itself.

    For example, if your script contained the following:

    PHP Code:
    <?php
     
    echo $_SERVER['argc'];
    And you ran it with the following arguments:

    Code:
    php myscript.php Alan Wagstaff TalkPHP
    Your script would output 4. The arguments it counts are "myscript.php", "Alan", "Wagstaff" and "TalkPHP".

    If we modify our script to use $_SERVER['argv'] (argument values) to print a list of the arguments we pass we can see this in action:

    PHP Code:
    <?php
     
    print_r
    ($_SERVER['argv'];
    If you now run the script with the following arguments:

    Code:
    php myscript.php Alan Wagstaff TalkPHP
    It should output something similar to:

    Code:
    Array
    (
        [0] => e:webroottalkphpcli_basicsmyscript.php
        [1] => Alan
        [2] => Wagstaff
        [3] => TalkPHP
    )
    As such, it's important to remember that when accessing your arguments in PHP CLI scripts, you need to start with $_SERVER['argv'][1] to get your first argument.


    Conclusion

    Hopefully this has given you an introduction to the basics of writing command line applications using PHP. For further reading on the PHP CLI, check out the links below.

    discuss this topic to forum

    relation tutorial

    No relevant information

    Category

      Ad Management (4)
      Calendars (3)
      Chat Systems (7)
      Content Management (6)
      Cookies and Sessions (8)
      Counters (8)
      Database Related (8)
      Date and Time (9)
      Development (13)
      Discussion Boards (8)
      E Commerce (8)
      Email Systems (13)
      Error Handling (7)
      File Manipulation (24)
      Flash and PHP (6)
      Form Processing (19)
      Guestbooks (12)
      Image Manipulation (21)
      Installing PHP (7)
      Introduction to PHP (23)
      Link Indexing (8)
      Mailing List Management (9)
      Miscellaneous (53)
      Networking (8)
      News Publishing (9)
      OOP (24)
      PEAR (6)
      PHP vs Other Languages (2)
      Polls and Voting (6)
      Postcards (1)
      Randomizing (14)
      Redirection (11)
      Searching (9)
      Security (29)
      Site Navigation (16)
      User Authentication (14)
      WAP and WML (7)
      Web Fetching (8)
      Web Traffic Analysis (15)
      XML and PHP (16)

    New

    Hot