Your first CLI script

Writing CLI scripts is, for the most part, similar to writing PHP scripts for web use - you have all the same functionality available to you as you would when writing for the web. As such, the scripts we're going to look at will specifically highlight special functionality and clever possibilities for the CLI SAPI.

To begin with, we are going to look at argc and argv - two variables oft overlooked in recent times. These two combined allow you to iterate through parameters passed to your script, with parameter 0 being the script itself.

    print "$argc arguments were passed. In order: \n";

    for ($i = 0; $i <= $argc -1; ++$i) {
        print "$i: $argv[$i]\n";

Save that in your public HTML directory as cli1.php. Note that you may need to amend the first line depending on where your CLI SAPI resides.

Line one is simply a shebang line (contraction of "sharp" (#) and "bang" (how else could you pronounce an exclamation mark?)) that points to where the CLI SAPI is on your system.

Line three prints the value of $argc out to the system. The usage of this becomes clear in lines four and five; it correlates directly to "the number of parameters passed to the script minus 1". It is minus one because $argv, the values of the parameters that were passed, is a zero-based array like all others in PHP.

In lines four and five, we use $argc to iterate through $argv and output each element as we go. So, with the script saved as cli1.php, run chmod like this:

chmod +x cli1.php

You should now be able to run the script by itself by typing:


For output, you should see:

1 arguments were passed. In order:
0: ./cli1.php

Try running the script again - this time, pass in random arguments. For example:

./cli1.php --foo --bar baz=wombat

This time, your output should be:

4 arguments were passed. In order:
0: ./cli1.php
1: --foo
2: --bar
3: baz=wombat

And so, as you can see, you have a building block upon which you can base your first shell application.


Next chapter: Advanced command-line parsing >>

Previous chapter: CLI SAPI differences

Jump to:


Home: Table of Contents

Copyright ©2015 Paul Hudson. Follow me: @twostraws.