Example 23-1. Script intended to be run
from command line (script.php)
#!/usr/bin/php
<?php
if ($argc != 2 || in_array($argv[1], array('--help', '-help',
'-h', '-?'))) {
?>
This is a command line PHP script with one option.
Usage:
<?php echo $argv[0]; ?> <option>
<option> can be some word you would like
to print out. With the --help, -help, -h,
or -? options, you can get this help.
<?php
} else {
echo $argv[1];
}
?>
In the script above, we used the special first line to indicate
that this file should be run by PHP. We work with a CLI
version here, so there will be no HTTP header printouts.
There are two variables you can use while writing command
line applications with PHP: $argc and $argv. The first is
the number of arguments plus one (the name of the script
running). The second is an array containing the arguments,
starting with the script name as number zero ($argv[0]).
In the program above we checked if there are less or more
than one arguments. Also if the argument was --help, -help,
-h or -?, we printed out the help message, printing the
script name dynamically. If we received some other argument
we echoed that out.
If you would like to run the above script on Unix, you
need to make it executable, and simply call it as script.php
echothis or script.php -h. On Windows, you can make a batch
file for this task:
Example 23-2. Batch file to run a command line PHP script
(script.bat)
@c:\php\cli\php.exe script.php %1 %2 %3 %4
Assuming you named the above program script.php, and you
have your CLI php.exe in c:\php\cli\php.exe this batch file
will run it for you with your added options: script.bat
echothis or script.bat -h.
See also the Readline extension documentation for more
functions you can use to enhance your command line applications
in PHP.