PHP is generally regarded as one of the most powerful and
easy-to-learn Web scripting technologies, and emphasis has largely been devoted
to using PHP on Web sites. However, the same power that can be harnessed to
handle complex Web sites can also be used on the command line. Like Perl, PHP
is a more-than-capable, dual-purpose scripting language.

There are a few minor caveats to using PHP on the command
line: the first is that you need to compile the PHP CLI binary (most Linux distributions
do). This will output the binary /usr/bin/php
which is the CLI interpreter to PHP scripts.

Writing a PHP CLI script is as simple as:

#!/usr/bin/php
<?php
...
?>

As you can see, about the only thing different from a Web
script is the “#!” identifier, which tells the shell to run the
script via the /usr/bin/php interpreter.
After that, it’s business as usual.

Two special variables are also available for use with
command-line arguments: $argc
contains the number of arguments provided to the script and $argv is an array of arguments that were
passed. Command-line arguments can be easily parsed as well. See Listing A for an example.

The example is fairly simplistic, but it illustrates how easy
it is to write comprehensive code for the command line. There are very few
limitations to what you can script on the command line, and nearly all
functions and modules that come with PHP are available for use. Certain
functions, such as those dealing with cookies, are not really applicable for
command-line use, but others such as database access and XML parsing certainly are.

Delivered each Tuesday, TechRepublic’s free Linux NetNote provides tips, articles, and other resources to help you hone your Linux skills. Automatically sign up today!