php command line mode

伊谢尔伦
Release: 2016-11-22 10:12:23
Original
1156 people have browsed it

Starting from version 4.3.0, PHP provides a new type of CLI SAPI (Server Application Programming Interface, server application programming port) support, named CLI, which means Command Line Interface, that is, command line interface. As the name suggests, the CLI SAPI module is mainly used as a development shell application for PHP. There are many differences between CLI SAPI and other CLI SAPI modules, which we will elaborate on in this chapter. It's worth mentioning that CLI and CGI are different SAPIs, although they share a lot of common behavior.

CLI SAPI was first released with PHP 4.2.0 version, but it is still only an experimental version and requires the --enable-cli parameter to be added when running ./configure. Starting from PHP version 4.3.0, CLI SAPI has become a formal module. The --enable-cli parameter will be set to on by default, and can also be blocked with the parameter --disable-cli.

Starting with PHP 4.3.0, the file name, location and presence of the CLI/CGI binary executable file will vary depending on how PHP is installed on the system. By default, when running make, CGI and CLI will be compiled and placed under sapi/cgi/php and sapi/cli/php respectively in the PHP source file directory. Notice that both files are named php. What happens during make install depends on the configuration line. If a SAPI module is selected during configuration, such as apxs, or the --disable-cgi parameter is used, the CLI will be copied to {PREFIX}/bin/php during the make install process, unless CGI has been placed In that position. So, for example, if you have --with--apxs in the configure line, the CLI will be copied to {PREFIX}/bin/php during make install. If you wish to undo the installation of the CGI executable, run make install-cli after make install. Alternatively, you can add the --disable-cgi parameter to the configuration line.

Note:

Since --enable-cli and --enable-cgi are both valid by default, there is no need to add --enable-cli to the configuration line to make the CLI copied to {PREFIX} during the make install process /bin/php.

In Windows distribution packages between PHP 4.2.0 and PHP 4.2.3, the file name of CLI is php-cli.exe, and php.exe in the same folder is CGI. Starting from PHP 4.3.0 version, the CLI execution file in the Windows distribution package is php.exe, which is placed in a separate folder named cli, that is, cli/php.exe. In PHP 5, the CLI exists in the home folder as php.exe, and the CGI version is called php-cgi.exe.

Starting from PHP 5, a new file named php-win.exe is released with the package. It is equivalent to the CLI version, but php-win does not output anything and therefore does not provide a console (no "DOS window" pops up). This approach is similar to php-gtk. It needs to be configured using the --enable-cli-win32 option.

Note: How do you know which SAPI you are using?

In the command line, run php -v to know whether the php is CGI or CLI. Please refer to the function php_sapi_name() and the constant PHP_SAPI.

Note:

The Unix man page has been added to PHP 4.3.2. You can type man php on the command line to view it.

The following are the significant differences between CLI SAPI and other CLI SAPI modules:

Unlike CGI SAPI, its output does not have any header information. Although the CGI SAPI provides a method to suppress HTTP header information, there is no similar method in the CLI SAPI to enable the output of HTTP header information. The CLI starts in quiet mode by default, but to ensure compatibility, the -q and --no-header parameters are still retained for backward compatibility, allowing the use of older CGI scripts. When running, the working directory will not be changed to the current directory of the script (you can use the -C and --no-chdir parameters to be compatible with CGI mode). Output plain text error message (not HTML format) when an error occurs.

CLI SAPI forcefully overrides certain settings in php.ini because these settings are meaningless in a shell environment.

Override php.ini setting options

Setting options

CLI SAPI default value

Remarks

html_errors FALSE Meaningless HTML tags will make the error message very cluttered, so read the error message under the shell is very difficult. Therefore change the default value of this option to FALSE.

implicit_flush TRUE In command line mode, all output from print and echo will be written to the output immediately without any buffering operations. If you wish to delay or control standard output, you can still use the output buffering setting.

max_execution_time 0 (infinite value) In view of the endless possibilities of using PHP in a shell environment, the maximum execution time is set to an infinite value. An application developed for the web may only take a few seconds to run, whereas a shell application may take much longer.

register_argc_argv TRUE Since this setting is TRUE, argc (the number of arguments passed to the application) and argv (the array containing the actual arguments) will always be accessible in the CLI SAPI. As of PHP 4.3.0, when using the CLI SAPI, the PHP variables $argc and $argv have been registered and set to the corresponding values. In previous versions, the establishment of these two variables in the CGI or module version relied on setting the PHP setting option register_globals to on. In addition to version and register_globals settings, they can be accessed at any time by calling $_SERVER or $HTTP_SERVER_VARS. For example: $_SERVER['argv']

Note:

These settings cannot be initialized to other values ​​in the settings file php.ini or any other specified file. These default values ​​are restricted to changes after all other settings files have been parsed. However, their values ​​can be changed while the program is running (although these settings are meaningless for that running process).

In order to ease the work in the shell environment, we have defined the following constants:

CLI-specific constants

Constant name

Description

STDIN An open stream pointing to stdin . It can be called with the following method:

<?php
    $stdin = fopen(&#39;php://stdin&#39;, &#39;r&#39;);
?>
Copy after login

If you want to read a line from stdin, you can use

<?php
$line = trim(fgets(STDIN)); // 从 STDIN 读取一行
fscanf(STDIN, "%d\n", $number); // 从 STDIN 读取数字
?>
Copy after login

STDOUT An open stream pointing to stdout. Can be called as follows:

<?php    
$stdout = fopen(&#39;php://stdout&#39;, &#39;w&#39;);
?>
Copy after login

STDERR An open stream pointing to stderr. It can be called in the following way:

<?php   
    $stderr = fopen(&#39;php://stderr&#39;, &#39;w&#39;);
?>
Copy after login

With the above constants, there is no need to create a stream pointing to stderr yourself. You can simply use these constants to replace the stream pointing:

php -r &#39;fwrite(STDERR, "stderr\n");&#39;
Copy after login

There is no need to close these streams yourself, PHP These operations are completed automatically.

CLI SAPI will not change the current directory to the directory where the run script is located. The following example shows the difference between this module and the CGI SAPI module:

<?php
    // 名为 test.php 的简单测试程序
    echo getcwd(), "\n";
?>
Copy after login

When using the CGI version, the output is

$ pwd
/tmp
$ php-cgi -f another_directory/test.php
/tmp/another_directory
Copy after login

You can obviously see that PHP changes the current directory to the directory where the script just ran is located.

Using CLI SAPI mode, you get:

$ pwd
/tmp
$ php -q another_directory/test.php
/tmp
Copy after login

This makes it very convenient when writing shell tools using PHP.

Note:

You can add the -C parameter to the CGI SAPI when running from the command line to make it support the CLI SAPI function.

The following are the command line mode option parameters provided by the PHP binary file (that is, the php.exe program). You can run the PHP command with the -h parameter at any time to query these parameters.

Usage: php [options] [-f] <file> [--] [args...]
       php [options] -r <code> [--] [args...]
       php [options] [-B <begin_code>] -R <code> [-E <end_code>] [--] [args...]
       php [options] [-B <begin_code>] -F <file> [-E <end_code>] [--] [args...]
       php [options] -- [args...]
       php [options] -a
  -a               Run interactively
  -c <path>|<file> Look for php.ini file in this directory
  -n               No php.ini file will be used
  -d foo[=bar]     Define INI entry foo with value &#39;bar&#39;
  -e               Generate extended information for debugger/profiler
  -f <file>        Parse <file>.
  -h               This help
  -i               PHP information
  -l               Syntax check only (lint)
  -m               Show compiled in modules
  -r <code>        Run PHP <code> without using script tags <?..?>
  -B <begin_code>  Run PHP <begin_code> before processing input lines
  -R <code>        Run PHP <code> for every input line
  -F <file>        Parse and execute <file> for every input line
  -E <end_code>    Run PHP <end_code> after processing all input lines
  -H               Hide any passed arguments from external tools.
  -s               Display colour syntax highlighted source.
  -v               Version number
  -w               Display source with stripped comments and whitespace.
  -z <file>        Load Zend extension <file>.
  args...          Arguments passed to script. Use -- args when first argument
                   starts with - or script is read from stdin
Copy after login

The CLI SAPI module has the following three different ways to get the PHP code to run:

Let PHP run the specified file.

php my_script.php
php -f my_script.php
Copy after login

Both of the above methods (with or without the -f parameter) can run the given my_script.php file. You can select any file to run. The specified PHP scripts do not have to have a .php extension. They can have any file name and extension.

Run PHP code directly from the command line.

php -r &#39;print_r(get_defined_constants());&#39;
Copy after login

When using this method, please pay attention to the substitution of shell variables and the use of quotation marks.

Note:

Please read the above example carefully, there are no start and end markers when running the code! With the -r parameter, these markers are unnecessary and will cause syntax errors.

Provide PHP code that needs to be run via standard input (stdin). The above usage provides very powerful functions, making it possible to dynamically generate PHP code and run these codes through the command line as shown in the following example:

$ some_application | some_filter | php | sort -u >final_output.txt
Copy after login

The above three methods of running code cannot be used at the same time.

Like all shell applications, the PHP binary (php.exe file) and the PHP script it runs can accept a series of parameters. PHP has no limit on the number of parameters passed to a script (the shell has a limit on the number of characters on the command line, but this limit is usually not exceeded). The arguments passed to the script are available in the global variable $argv. The zero-indexed member of this array is the name of the script (when the PHP code comes from standard input and is run directly from the command line with the -r parameter, the name is "-"). In addition, the global variable $argc stores the number of member variables in the $argv array (not the number of parameters passed to the script program).

只要传送给脚本的参数不是以 - 符号开头,就无需过多的注意什么。向脚本传送以 - 开头的参数会导致错误,因为 PHP 会认为应该由它自身来处理这些参数。可以用参数列表分隔符 -- 来解决这个问题。在 PHP 解析完参数后,该符号后所有的参数将会被原样传送给脚本程序。

# 以下命令将不会运行 PHP 代码,而只显示 PHP 命令行模式的使用说明:
$ php -r &#39;var_dump($argv);&#39; -h
Usage: php [options] [-f] <file> [args...]
[...]
# 以下命令将会把“-h”参数传送给脚本程序,PHP 不会显示命令行模式的使用说明:
$ php -r &#39;var_dump($argv);&#39; -- -h
array(2) {
  [0]=>
  string(1) "-"
  [1]=>
  string(2) "-h"
}
Copy after login

除此之外,还有另一个方法将 PHP 用于外壳脚本。可以在写一个脚本,并在第一行以 #!/usr/bin/php 开头,在其后加上以 PHP 开始和结尾标记符包含的正常的 PHP 代码,然后为该文件设置正确的运行属性(例如:chmod +x test)。该方法可以使得该文件能够像外壳脚本或 PERL 脚本一样被直接执行。

#!/usr/bin/php
<?php
    var_dump($argv);
?>
Copy after login

假设改文件名为 test 并被放置在当前目录下,可以做如下操作:

$ chmod +x test
$ ./test -h -- foo
array(4) {
  [0]=>
  string(6) "./test"
  [1]=>
  string(2) "-h"
  [2]=>
  string(2) "--"
  [3]=>
  string(3) "foo"
}
Copy after login

正如所看到的,在向该脚本传送以 - 开头的参数时,脚本仍然能够正常运行。

PHP 4.3.3 以来有效的长选项:

命令行选项

选项名称

长名称

说明

-a --interactive 交互式运行 PHP。如果编译 PHP 时加入了 Readline 扩展(Windows 下不可用),那将会得到一个很好的外壳,包括一个自动完成的功能(例如可以在键入变量名的时候,按下 TAB 键,PHP 会自动完成该变量名)以及命令历史记录,可以用上下键来访问。历史记录存在 ~/.php_history 文件中。

Note:

通过 auto_prepend_file 和 auto_append_file 包含的文件在此模式下会被解析,但有些限制,例如函数必须在被调用之前定义。

-c --php-ini 用该参数,可以指定一个放置 php.ini 文件的目录,或者直接指定一个自定义的 INI 文件(其文件名可以不是 php.ini),例如:

$ php -c /custom/directory/ my_script.php
$ php -c /custom/directory/custom-file.ini my_script.php
Copy after login

如果不指定此选项,PHP 将在默认位置搜索文件。

-n --no-php-ini 完全忽略 php.ini。此参数在 PHP 4.3.0 以后有效。

-d --define 用该参数可以自行设置任何可以在 php.ini 文件中设置的配置选项的值,其语法为:

-d configuration_directive[=value]
Copy after login

例子(因版面原因而折行显示):

# 取值部分被省略,将会把配置选项设为 "1"
$ php -d max_execution_time
        -r &#39;$foo = ini_get("max_execution_time"); var_dump($foo);&#39;
string(1) "1"
# 取值部分为空白,将会把配置选项设为 ""
php -d max_execution_time=
        -r &#39;$foo = ini_get("max_execution_time"); var_dump($foo);&#39;
string(0) ""
# 配置选项将被设置成为任何 &#39;=&#39; 字符之后的值
$  php -d max_execution_time=20
        -r &#39;$foo = ini_get("max_execution_time"); var_dump($foo);&#39;
string(2) "20"
$  php
        -d max_execution_time=doesntmakesense
        -r &#39;$foo = ini_get("max_execution_time"); var_dump($foo);&#39;
string(15) "doesntmakesense"
Copy after login

-e --profile-info 激活扩展信息模式,被用于调试/测试。

-f --file 解析并运行 -f 选项给定的文件名。该参数为可选参数,可以省略,仅指明需要运行的文件名即可。

-h and -? --help and --usage 使用该参数,可以得到完整的命令行参数的列表及这些参数作用的简单描述。

-i --info 该命令行参数会调用 phpinfo() 函数并显示出结果。如果 PHP 没有正常工作,建议执行 php -i 命令来查看在信息表格之前或者对应的地方是否有任何错误信息输出。请注意当使用 CGI 摸索时,输出的内容为 HTML 格式,因此输出的信息篇幅较大。

-l --syntax-check 该参数提供了对指定 PHP 代码进行语法检查的方便的方法。如果成功,则向标准输出写入 No syntax errors detected in 字符串,并且外壳返回值为 0。如果失败,则输出 Errors parsing 以及内部解析器错误信息到标准输出,同时外壳返回值将别设置为 255。该参数将无法检查致命错误(如未定义函数),如果也希望检测致命错误,请使用 -f 参数。

Note:

该参数不能和 -r 一同使用。

-m --modules 使用该参数,PHP 将打印出内置以及已加载的 PHP 及 Zend 模块:

$ php -m
[PHP Modules]
xml
tokenizer
standard
session
posix
pcre
overload
mysql
mbstring
ctype
[Zend Modules]
Copy after login

-r --run 使用该参数可以在命令行内运行单行 PHP 代码。无需加上 PHP 的起始和结束标识符(),否则将会导致语法解析错误。

Note:

使用这种形式的 PHP 时,应注意避免和外壳环境进行的命令行参数替换相冲突。

显示语法解析错误的范例

$ php -r "$foo = get_defined_constants();"
Command line code(1) : Parse error - parse error, unexpected &#39;=&#39;
Copy after login

这里的问题在于即使使用了双引号 ",sh/bash 仍然实行了参数替换。由于 $foo 没有被定义,被替换后它所在的位置变成了空字符,因此在运行时,实际被 PHP 读取的代码为:

$ php -r " = get_defined_constants();"
Copy after login

正确的方法是使用单引号 '。在用单引号引用的字符串中,变量不会被 sh/bash 还原成其原值。

$ php -r &#39;$foo = get_defined_constants(); var_dump($foo);&#39;
array(370) {
  ["E_ERROR"]=>
  int(1)
  ["E_WARNING"]=>
  int(2)
  ["E_PARSE"]=>
  int(4)
  ["E_NOTICE"]=>
  int(8)
  ["E_CORE_ERROR"]=>
  [...]
Copy after login

如果使用的外壳不是 sh/bash,可能会碰到更多问题。请将碰到的 Bug 向 » http://bugs.php.net/ 报告。注意,当试图将 shell 变量用到代码中或者使用反斜线时仍然很容易碰到问题。

Note:

-r 在 CLI SAPI 中有效,在 CGI SAPI 中无效。

Note:

此选项只用于非常基本的用途。因此一些配置指令(例如 auto_prepend_file 和 auto_append_file)在此模式下被忽略。

-B --process-begin 在处理 stdin 之前先执行 PHP 代码。PHP 5 新加。

-R --process-code 对每个输入行都执行 PHP 代码。PHP 5 新加。此模式下有两个特殊变量:$argn 和 $argi。$argn 包含 PHP 当前处理的行内容,而 $argi 则包含该行号。

-F --process-file 对每个输入行都执行 PHP 文件。PHP 5 新加。

-E --process-end 在处理完输入后执行的 PHP 代码。PHP 5 新加。使用 -B ,-R 和 -E 选项来计算一个项目总行数的例子。

$ find my_proj | php -B &#39;$l=0;&#39; -R &#39;$l += count(@file($argn));&#39; -E &#39;echo "Total Lines: $l\n";&#39;Total Lines: 37328
Copy after login

-s --syntax-highlight and --syntax-highlight 显示有语法高亮色彩的源代码。该参数使用内建机制来解析文件并为其生成一个 HTML 高亮版本并将结果写到标准输出。请注意该过程所做的只是生成了一个 [...] 的 HTML 标记的块,并不包含任何的 HTML 头。

Note:

该选项不能和 -r 参数同时使用。

-v --version 将 PHP,PHP SAPI 和 Zend 的版本信息写入标准输出。例如:

$ php -v
PHP 4.3.0 (cli), Copyright (c) 1997-2002 The PHP GroupZend Engine v1.3.0, Copyright (c) 1998-2002 Zend Technologies
Copy after login

-w --strip 显示除去了注释和多余空白的源代码。

Note:

该选项不能和 -r 参数同时使用。

-z --zend-extension 加载 Zend 扩展库。如果仅给定一个文件名,PHP 将试图从当前系统扩展库的默认路径(在 Linux 系统下,该路径通常由 /etc/ld.so.conf 指定)加载该扩展库。如果用一个绝对路径指定文件名,则不会使用系统的扩展库默认路径。如果用相对路径指定的文件名,则 PHP 仅试图在当前目录的相对目录加载扩展库。

PHP 的命令行模式能使得 PHP 脚本能完全独立于 web 服务器单独运行。如果使用 Unix 系统,需要在 PHP 脚本的最前面加上一行特殊的代码,使得它能够被执行,这样系统就能知道用哪个程序去运行该脚本。在 Windows 平台下可以将 php.exe 和 .php 文件的双击属性相关联,也可以编写一个批处理文件来用 PHP 执行脚本。为 Unix 系统增加的第一行代码不会影响该脚本在 Windows 下的运行,因此也可以用该方法编写跨平台的脚本程序。以下是一个简单的 PHP 命令行程序的范例。

Example #1 试图以命令行方式运行的 PHP 脚本(script.php)

#!/usr/bin/php
<?php
if ($argc != 2 || in_array($argv[1], array(&#39;--help&#39;, &#39;-help&#39;, &#39;-h&#39;, &#39;-?&#39;))) {
?>
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];
}
?>
Copy after login

在以上脚本中,用第一行特殊的代码来指明该文件应该由 PHP 来执行。在这里使用 CLI 的版本,因此不会有 HTTP 头信息输出。在用 PHP 编写命令行应用程序时,可以使用两个参数:$argc 和 $argv。前面一个的值是比参数个数大 1 的整数(运行的脚本本身的名称也被当作一个参数)。第二个是包含有参数的数组,其第一个元素为脚本的名称,下标为数字 0($argv[0])。

以上程序中检查了参数的个数是大于 1 个还是小于 1 个。此外如果参数是 --help ,-help ,-h 或 -? 时,打印出帮助信息,并同时动态输出脚本的名称。如果还收到了其它参数,将其显示出来。

如果希望在 Unix 下运行以上脚本,需要使其属性为可执行文件,然后简单的运行 script.php echothis 或 script.php -h。在 Windows 下,可以为此编写一个批处理文件:

Example #2 运行 PHP 命令行脚本的批处理文件(script.bat)

@C:\php\php.exe script.php %1 %2 %3 %
Copy after login

假设将上述程序命名为 script.php,且 CLI 版的 php.exe 文件放置在 c:\php\cli\php.exe,该批处理文件会帮助将附加的参数传给脚本程序:script.bat echothis 或 script.bat -h。


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!