Home > Backend Development > PHP Tutorial > Detailed explanation of command line mode in PHP

Detailed explanation of command line mode in PHP

小云云
Release: 2023-03-21 06:54:01
Original
3795 people have browsed it

This article mainly shares with you a detailed explanation of the command line mode in PHP. The following are the command line mode option parameters provided by the PHP binary file (that is, the php.exe program). You can query these parameters at any time through the PHP -h command.

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 &#39;bar&#39;
  -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
Copy after login

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

In the windows environment, try to use double quotes, and in the linux environment, try to use single quotes.

  1. 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 choose any file to run. The PHP scripts you specify do not have to have a .php extension; they can have any file name and extension.

  2. Run PHP code directly from the command line.

    php -r "print_r(get_defined_constants());"
    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 a syntax error.

  3. Provide the PHP code that needs to be run through standard input (stdin).

    The above usage provides us with very powerful functions, allowing us 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 arguments passed to a script (the shell has a limit on the number of characters on the command line, but you usually won't exceed that limit). The arguments passed to your script are available in the global variable $argv. The zero-indexed member of this array is the name of the script (this name is "-" when the PHP code comes from standard input and is run directly from the command line with the -r parameter). 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).

As long as the parameters you pass to your script do not start with a - symbol, you don't need to pay too much attention to anything. Passing parameters starting with - to your script will cause an error because PHP will think it should handle these parameters itself. You can use the parameter list separator -- to solve this problem. After PHP parses the parameters, all parameters after this symbol will be passed to your script as is.

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

Apart from this, we have another way to use PHP for shell scripts. You can write a script and start the first line with #!/usr/bin/php, followed by normal PHP code with PHP start and end tags, and then set up the correct execution for the file Attributes. This method enables the file to be executed directly like a shell script or PERL script.

!/usr/bin/php
var_dump($argv);
?>

Assuming the file name is changed to test and placed in the current directory, we can do the following:

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

As you can see, when you pass parameters starting with - to the script, the script still runs normally.

Table 23-3. Command line options

Option nameDescription
-s

Display source files with syntax highlighting.

This parameter uses the built-in mechanism to parse the file and generate an HTML highlighted version of it and write the result to standard output. Please note that all this process does is generate an HTML tag block of [...] and does not include any HTML headers.

Note: This option cannot be used together with the -r parameter.

-w

#Displays the source code with comments and spaces removed.

Note: This option cannot be used together with the -r parameter.

-f

#Parse and run the given filename. This parameter is optional and does not need to be added. It only needs to specify the file name that needs to be run.

-v

Write the version information of PHP, PHP SAPI and Zend to the standard output. For example:

$ php -v PHP 4.3.0-dev (cli), Copyright (c) 1997-2002 The PHP Group Zend Engine v1.3.0, Copyright (c) 1998-2002 Zend Technologies
-c

With this parameter, you can specify a place to place the php.ini file directory, or directly specify a custom INI file whose file name does not need to be php.ini. For example:

$ php -c /custom/directory/ my_script.php $ php -c /custom/directory/custom-file.ini my_script.php
-a

Run PHP interactively.

-d

Use this parameter to set the value of the variable in the php.ini file. The syntax is:

-d configuration_directive[=value]

Example:

# Ommiting the value part will set the given configuration directive to "1" $ php -d max_execution_time -r '$foo = ini_get("max_execution_time"); var_dump($foo);' string(1) "1" # Passing an empty value part will set the configuration directive to "" php -d max_execution_time= -r '$foo = ini_get("max_execution_time"); var_dump($foo);' string(0) "" # The configuration directive will be set to anything passed after the '=' character $ php -d max_execution_time=20 -r '$foo = ini_get("max_execution_time"); var_dump($foo);' string(2) "20" $ php -d max_execution_time=doesntmakesense -r '$foo = ini_get("max_execution_time"); var_dump($foo);' string(15) "doesntmakesense"
-e

Generate extended information for debuggers, etc.

-z

Load the Zend extension library. If only a filename is given, PHP will attempt to load the extension library from the default path of your system's extension library (on Linux systems, this path is usually specified by /etc/ld.so.conf). If you specify a filename with an absolute path, the system's default path to the extension library will not be used. If you specify a filename with a relative path, PHP will only try to load the extension relative to the current directory.

-l

This parameter provides a convenient method for syntax checking of the specified PHP code. If successful, the string No syntax errors detected in is written to standard output, and the shell returns a value of 0. If it fails, Errors parsing will be written to standard output along with internal parser error messages, and the shell return value will be set to 255.

This parameter will not be able to check for fatal errors (such as undefined functions). If you want to detect fatal errors, please use the -f parameter.

Note: This parameter cannot be used together with -r.

-m

Using this parameter, PHP will print out the built-in and loaded PHP and Zend modules:

$ php -m [PHP Modules] xml tokenizer standard session posix pcre overload mysql mbstring ctype [Zend Modules]
-i该命令行参数会调用 phpinfo() 函数,并打印出结果。如果 PHP 没有正常工作,我们建议您执行 php -i 命令来查看在信息表格之前或者对应的地方是否有任何错误信息输出。请注意输出的内容为 HTML 格式,因此输出的信息篇幅较大。
-r

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

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

显示语法解析错误的范例

$ php -r "$foo = get_defined_constants();" Command line code(1) : Parse error - parse error, unexpected '='

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

$ php -r " = get_defined_constants();"

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

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

如果您使用的外壳不是 sh/bash,您可能会碰到其它的问题。请报告您碰到的 bug,或者发邮件到 phpdoc@lists.php.net。

当您试图将外壳的环境变量引入到马或者用反斜线来转义字符时也可能碰到各种各样的问题,请您在使用时注意!

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

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


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

例子 23-1. 试图以命令行方式运行的 PHP 脚本(script.php)
#!/usr/bin/php<?phpif ($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 下,您可以为此编写一个批处理文件:

@c:\php\cli\php.exe script.php %1 %2 %3 %4
Copy after login

相关推荐:

关于命令行模式的详细介绍

php命令行模式

PHP 5 PHP的命令行模式解决办法

The above is the detailed content of Detailed explanation of command line mode in PHP. For more information, please follow other related articles on the PHP Chinese website!

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