search
HomeBackend DevelopmentPHP TutorialDetailed explanation of PHP command line execution

Detailed explanation of PHP command line execution

Mar 10, 2018 am 11:55 AM
phpCommand Lineimplement

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></code></code></file></file></file></path></file></file></code></file></span>

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

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

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

假设改文件名为 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/>

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 Name Description
##-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/>
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!

Statement
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
PHP's Current Status: A Look at Web Development TrendsPHP's Current Status: A Look at Web Development TrendsApr 13, 2025 am 12:20 AM

PHP remains important in modern web development, especially in content management and e-commerce platforms. 1) PHP has a rich ecosystem and strong framework support, such as Laravel and Symfony. 2) Performance optimization can be achieved through OPcache and Nginx. 3) PHP8.0 introduces JIT compiler to improve performance. 4) Cloud-native applications are deployed through Docker and Kubernetes to improve flexibility and scalability.

PHP vs. Other Languages: A ComparisonPHP vs. Other Languages: A ComparisonApr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and FunctionalityPHP vs. Python: Core Features and FunctionalityApr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP: A Key Language for Web DevelopmentPHP: A Key Language for Web DevelopmentApr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP: The Foundation of Many WebsitesPHP: The Foundation of Many WebsitesApr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

Beyond the Hype: Assessing PHP's Role TodayBeyond the Hype: Assessing PHP's Role TodayApr 12, 2025 am 12:17 AM

PHP remains a powerful and widely used tool in modern programming, especially in the field of web development. 1) PHP is easy to use and seamlessly integrated with databases, and is the first choice for many developers. 2) It supports dynamic content generation and object-oriented programming, suitable for quickly creating and maintaining websites. 3) PHP's performance can be improved by caching and optimizing database queries, and its extensive community and rich ecosystem make it still important in today's technology stack.

What are Weak References in PHP and when are they useful?What are Weak References in PHP and when are they useful?Apr 12, 2025 am 12:13 AM

In PHP, weak references are implemented through the WeakReference class and will not prevent the garbage collector from reclaiming objects. Weak references are suitable for scenarios such as caching systems and event listeners. It should be noted that it cannot guarantee the survival of objects and that garbage collection may be delayed.

Explain the __invoke magic method in PHP.Explain the __invoke magic method in PHP.Apr 12, 2025 am 12:07 AM

The \_\_invoke method allows objects to be called like functions. 1. Define the \_\_invoke method so that the object can be called. 2. When using the $obj(...) syntax, PHP will execute the \_\_invoke method. 3. Suitable for scenarios such as logging and calculator, improving code flexibility and readability.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft