As of version 4.3.0, PHP
supports a new SAPI type (Server
Application Programming Interface) named
CLI which means Command Line Interface. As the name
implies, this SAPI type main focus
is on developing shell (or desktop as well) applications with
PHP. There are quite a few
differences between the CLI SAPI and
other SAPIs which are explained in
this chapter. It's worth mentioning that
CLI and CGI are different
SAPI's although they do share many of the same behaviors.
The CLI SAPI was released for
the first time with PHP 4.2.0, but
was still experimental and had to be explicitly enabled with
--enable-cli when running ./configure. Since PHP
4.3.0 the CLI SAPI is no longer
experimental and the option
--enable-cli is on by default. You may use --disable-cli to disable it.
As of PHP 4.3.0, the name, location and existence of the
CLI/CGI binaries will differ depending on how PHP is
installed on your system. By default when executing make, both the CGI and CLI are built and
placed as sapi/cgi/php and sapi/cli/php respectively, in your php
source directory. You will note that both are named php. What happens during make install depends on your configure line.
If a module SAPI is chosen during configure, such as apxs, or
the --disable-cgi option is used,
the CLI is copied to
{PREFIX}/bin/php during make
install otherwise the CGI is placed there. So, for
example, if --with--apxs is in your
configure line then the CLI is copied to
{PREFIX}/bin/php during make
install. If you want to override the installation of the
CGI binary, use make install-cli
after make install. Alternatively
you can specify --disable-cgi in
your configure line.
注: Because both --enable-cli and --enable-cgi are enabled by default, simply having --enable-cli in your configure line does not necessarily mean the CLI will be copied as {PREFIX}/bin/php during make install.
The windows package distributes the CGI as php.exe and
has a folder named cli with the CLI in it, so: cli/php.exe.
What SAPI do I have?: From a shell, typing php -v will tell you whether php is CGI or CLI. See also the function php_sapi_name() and the constant PHP_SAPI.
Remarkable differences of the CLI
SAPI compared to other
SAPIs:
Unlike the CGI SAPI, no
headers are written to the output.
Though the CGI SAPI
provides a way to suppress HTTP headers, there's no
equivalent switch to enable them in the CLI SAPI.
CLI is started up in quiet mode by default, though
the -q switch is kept for
compatibility so that you can use older CGI scripts.
It does not change the working directory to that of
the script. (-C switch kept for
compatibility)
Plain text error messages (no HTML formatting).
There are certain php.ini
directives which are overriden by the CLI SAPI because they do not make sense in
shell environments:
表格 23-1. Overriden
php.ini directives
|
注: These directives cannot be initialized with another value from the configuration file php.ini or a custom one (if specified). This is a limitation because those default values are applied after all configuration files have been parsed. However, their value can be changed during runtime (which does not make sense for all of those directives, e.g. register_argc_argv).
To ease working in the shell environment, the
following constants are defined:
表格 23-2. CLI specific Constants
An already opened stream to stdin. This saves opening it
with
|
||
An already opened stream to stdout. This saves opening it
with
|
||
An already opened stream to stderr. This saves opening it
with
|
Given the above, you don't need to open e.g. a
stream for stderr yourself but
simply use the constant instead of the stream
resource:
php -r 'fwrite(STDERR, "stderr\n");' |
The CLI SAPI does not change
the current directory to the directory of the executed
script!
Example showing the difference to the CGI SAPI:
?php /* Our simple test application named test.php*/ echo getcwd(), "\n"; ? |
When using the CGI version,
the output is:
$ pwd /tmp $ php -q another_directory/test.php /tmp/another_directory |
Using the CLI SAPI
yields:
$ pwd /tmp $ php -f another_directory/test.php /tmp |
注: The CGI SAPI supports the CLI SAPI behaviour by means of the -C switch when run from the command line.
The list of command line options provided by the PHP binary can be queried anytime by
running PHP with the -h switch:
Usage: php [options] [-f] file [args...] php [options] -r code [args...] php [options] [-- args...] -s Display colour syntax highlighted source. -w Display source with stripped comments and whitespace. -f file Parse file . -v Version number -c path | file Look for php.ini file in this directory -a Run interactively -d foo[=bar] Define INI entry foo with value 'bar' -e Generate extended information for debugger/profiler -z file Load Zend extension file . -l Syntax check only (lint) -m Show compiled in modules -i PHP information -r code Run PHP code without using script tags ?..? -h This help args... Arguments passed to script. Use -- args when first argument starts with - or script is read from stdin |
The CLI SAPI has three
different ways of getting the PHP
code you want to execute:
Telling PHP to execute a
certain file.
Pass the PHP code to
execute directly on the command line.
php -r 'print_r(get_defined_constants());' |
注: Read the example carefully, there are no beginning or ending tags! The -r switch simply does not need them. Using them will lead to a parser error.
Provide the PHP code to
execute via standard input (stdin).
This gives the powerful ability to dynamically
create PHP code and feed it to
the binary, as shown in this (fictional) example:
Like every shell application, the
PHP binary accepts a number of arguments but your PHP script can also receive arguments.
The number of arguments which can be passed to your script is
not limited by PHP (the shell has a
certain size limit in the number of characters which can be
passed; usually you won't hit this limit). The arguments
passed to your script are available in the global array $argv. The zero index always contains
the script name (which is - in case
the PHP code is coming from either
standard input or from the command line switch -r). The second registered global variable is
$argc which contains the number of
elements in the $argv array (not the number
of arguments passed to the script).
As long as the arguments you want to pass to your script
do not start with the - character,
there's nothing special to watch out for. Passing an argument
to your script which starts with a -
will cause trouble because PHP
itself thinks it has to handle it. To prevent this, use the
argument list separator --. After
this separator has been parsed by
PHP, every argument following it is passed untouched to
your script.
# This will not execute the given code but will show the PHP usage $ php -r 'var_dump($argv);' -h Usage: php [options] [-f] file [args...] [...] # This will pass the '-h' argument to your script and prevent PHP from showing it's usage $ php -r 'var_dump($argv);' -- -h array(2) { [0]= string(1) "-" [1]= string(2) "-h" } |
However, there's another way of using PHP for shell scripting. You can write a
script where the first line starts with
#!/usr/bin/php. Following this you can place normal PHP code included within the PHP starting and end tags. Once you have set
the execution attributes of the file appropriately (e.g. chmod +x test) your script can be
executed like a normal shell or perl script:
#!/usr/bin/php ?php var_dump($argv); ? |
$ chmod 755 test $ ./test -h -- foo array(4) { [0]= string(6) "./test" [1]= string(2) "-h" [2]= string(2) "--" [3]= string(3) "foo" } |
表格 23-3. Command line options
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
The PHP executable can be used to run PHP scripts
absolutely independent from the web server. If you are on a
Unix system, you should add a special first line to your PHP
script, and make it executable, so the system will know, what
program should run the script. On a Windows platform you can
associate php.exe with the double
click option of the .php files, or
you can make a batch file to run the script through PHP. The
first line added to the script to work on Unix won't hurt on
Windows, so you can write cross platform programs this way. A
simple example of writing a command line PHP program can be
found below.
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:
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.