Writing Scripts for the Command Line

The PHP language provides certain functionality that is particularly useful for writing command-line scripts. You will rarely, if ever, use these features in the web environment, but they are described in the following sections.

Character Mode Output

When you're producing web output, you use the <br> tag to produce a simple line break in the output. When it is sent to a web page, the newline character, \n, causes a line break in the HTML source, but it is not visible in the rendered web page.

Command-line scripts, however, produce text-only output, so you must use the newline character to format your output. If your script produces any output, you should always include \n after the last item has been displayed.

You can also take advantage of the fixed-width character mode when running command-line scriptsfor instance, by spacing output into columns. The printf function allows you to use width and alignment format characters, which have no effect on HTML output unless they're contained in <PRE> tags. For more information, refer to Lesson 6, "Working with Strings."

Command-Line Arguments

You can pass arguments to a shell script by simply appending them after the script name itself. The number of arguments passed can be found in the variable $argc, and the arguments themselves are stored in a numerically indexed array named $argv.

Arguments The identifier names argc and argv are used for historic reasons. They originated in C and are now widely used in many programming languages.

In PHP $argc is assigned for convenience only; you could, of course, perform count($argv) to find out how many arguments were passed to the script.

The $argv array will always contain at least one element. Even if no additional arguments are passed to the script, $argv[0] will contain the name of the script itself, and $argc will be 1.

The script in Listing 21.1 requires exactly two arguments to be passed. Otherwise, an error message appears, and the script terminates. The output produced shows which of the two arguments is greater.

Listing 21.1. Using Command-Line Arguments
 #!/usr/local/bin/php <?php if ($argc != 3) {   echo $argv[0].": Must provide exactly two arguments\n";   exit; } if ($argv[1] < $argv[2]) {   echo $argv[1] . " is less than ". $argv[2] . "\n"; } elseif ($argv[1] > $argv[2]) {   echo $argv[1] . " is greater than ". $argv[2] . "\n"; } else {   echo $argv[1] . " is equal to ". $argv[2] . "\n"; } ?> 

Notice that the initial condition in Listing 21.1 checks that the value of $argc is 3; there must be two arguments, plus the script name itself in $argv[0]. In fact, $argv[0] is output as part of the error message. This is a useful technique for ensuring that the actual script name is shown, whatever its name happens to be.

Input/Output Streams

Although it is possible to read and write directly to the standard input, output, and error streams in the web environment, doing so is much more useful in command-line scripts.

Stream access is performed using the same set of functions as for file access: You simply open a file pointer to the appropriate stream and manipulate it in the same way.

The stream identifiers look like URLsremember that PHP also allows you to open URLs by using the file access functionsconstructed of php:// followed by the name of the stream. For instance, to open the standard input stream for reading, you use the following command:

 $fp = fopen("php://stdin", "r"); 

However, because stream access is common in command-line scripts, PHP provides a shortcut. The constants STDIN, STDOUT, and STDERR provide instant access to an opened stream without requiring a call to fopen.

The script in Listing 21.2 uses all three standard streams. It reads data from standard input and capitalizes the letters it contains by using strtoupper. If the input data contains non-alphanumeric characters, a warning is sent to the standard error stream as well.

Listing 21.2. Reading and Writing Standard Streams
 #!/usr/local/bin/php <?php while (!feof(STDIN)) {   $line++;   $data = trim(fgets(STDIN));   fputs(STDOUT, strtoupper($data)."\n");   if (!ereg("^[[:alnum:]]+$", $data)) {     fputs(STDERR,        "Warning: Invalid characters on line $line\n");   } } ?> 

If you run this script from the command line, it waits for you to type data a line at a time, and it returns the uppercase version after each line is entered. The advantage of using the standard input stream is that you can redirect input from another source.

To pass the contents of the file myfile into a script named myscript and have the output written to outfile, for instance, you would run the following command:

 $ myscript < myfile > outfile 

With the example in Listing 21.2, outfile would contain only the uppercase data. The warning messages produced would continue to be displayed to screen, unless you also redirected standard error.

To summarize, the constants and stream identifiers available in command-line PHP are shown in Table 21.1.

Table 21.1. Stream Access for CLI PHP






Standard input



Standard output



Standard error

Creating Desktop Applications

PHP is such a powerful language that you can even use it to create desktop applications. Furthermore, because PHP is an interpreted language, any such applications are likely to be highly portable.

The PHP-GTK extension implements an interface to the GIMP window toolkit, GTK+. This provides PHP developers with the ability to create applications with a graphical front end that includes windows, menus, buttons, and even drag-and-drop functionality.

Creating a complex graphical application is beyond the scope of this book. If you are interested in learning more about PHP-GTK, however, see http://gtk.php.net.

    Sams Teach Yourself PHP in 10 Minutes
    Sams Teach Yourself PHP in 10 Minutes
    ISBN: 0672327627
    EAN: 2147483647
    Year: 2005
    Pages: 151
    Authors: Chris Newman

    Similar book on Amazon

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net