Detailed explanation of PHP command line execution

小云云
Release: 2023-03-21 07:44:01
Original
4604 people have browsed it

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.

<span style="font-size: 14px;">Usage: php [options] [-f] <file> [args...]<br>       php [options] -r <code> [args...]<br>       php [options] [-- args...]<br>  -s               Display colour syntax highlighted source.<br>  -w               Display source with stripped comments and whitespace.<br>  -f <file>        Parse <file>.<br>  -v               Version number<br>  -c <path>|<file> Look for php.ini file in this directory<br>  -a               Run interactively<br>  -d foo[=bar]     Define INI entry foo with value 'bar'<br>  -e               Generate extended information for debugger/profiler<br>  -z <file>        Load Zend extension <file>.<br>  -l               Syntax check only (lint)<br>  -m               Show compiled in modules<br>  -i               PHP information<br>  -r <code>        Run PHP <code> without using script tags <?..?><br>  -h               This help<br> <br>  args...          Arguments passed to script. Use -- args when first argument <br>                   starts with - or script is read from stdin<br></span>
Copy after login

## CLI The SAPI module has the following three different methods to obtain your PHP code to be 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.

    <span style="font-size: 14px;">php my_script.php <br/>php -f  "my_script.php"<br/></span>
    Copy after login
    ##The above two methods (with or without the -f parameter) are able to run a 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 on the command line.

    <span style="font-size: 14px;">php -r "print_r(get_defined_constants());"<br/></span>
    Copy after login
    When using this method, please pay attention to the shell variables Substitutions and 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.

  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
  4. ## 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 (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).

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. 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.

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

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

#!/usr/bin/php<br/>
<br/>
Copy after login
Copy after login
rgv);<br/>?>

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

$ chmod 755 test<br/>$ ./test -h -- foo<br/>array(4) {<br/>  [0]=><br/>  string(6) "./test"<br/>  [1]=><br/>  string(2) "-h"<br/>  [2]=><br/>  string(2) "--"<br/>  [3]=><br/>  string(3) "foo"<br/>}<br/>
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

##-w-f## Parses and runs 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##Use this parameter to set the variables in the php.ini file yourself The value, the syntax is: ##-m##-i-r
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 contain any HTML headers.

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

Display source code with comments and spaces removed .

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

##Write the version information of PHP, PHP SAPI and Zend 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
Use For this parameter, you can specify a directory where the php.ini file is placed, or directly specify a custom INI file whose file name may not 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

-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 try 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 syntax checking for the specified PHP code Convenient method. 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 with -r.

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

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

This command line parameter will call the phpinfo() function and print out result. If PHP is not working properly, we recommend that you execute php -i command to see if there is any error message output before the information table or in the corresponding place. Please note that the output content is in HTML format, so the output information is larger.
##Use this parameter to run PHP code on the command line. You do not need to add the PHP starting and ending identifiers (), otherwise it will cause syntax parsing errors.

注: 使用这种形式的 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_defi
<br/>
Copy after login
Copy after login
ned_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/phpThis is a command line PHP script with one option.  Usage:   

In the above script, we use the first special line of code to indicate that the file should be executed by PHP. We are using the CLI version here, so no HTTP headers will be output. When you write command line applications in PHP, you can use two parameters: $argc and $argv. The value of the previous one is an integer one greater than the number of parameters (the name of the script being run is also considered a parameter). The second one contains an array of parameters, the first element of which is the name of the script, and the subscript is the number 0 ($argv[0]).

In the above program we checked whether the number of parameters is greater than 1 or less than 1. Even if the parameter is --help, -help, -h or -?, we still print out the help information and dynamically output the name of the script at the same time. If other parameters are received, we also display them.

If you want to run the above script under Unix, you need to make it an executable script, and then simply run script.php echothis or script.php -h. Under Windows, you can write a batch file for this:

Related recommendations:

Execute based on command line with parameters Method of php script and obtaining parameters

Method of executing php script with parameters based on command line and obtaining parameters, php script_PHP tutorial

Command line execution on PHP

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

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!