Command line execution under PHP

不言
Release: 2023-03-25 17:54:02
Original
1971 people have browsed it

This article mainly introduces the command line execution under PHP, which has certain reference value. Now I share it with everyone. Friends in need can refer to it

The following is PHP The command line mode option parameters provided by the binary file (i.e. 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

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

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
    The above two methods (with or without the

    -f parameter) are both Able to run the given my_script.php file. You can choose any file to run. The PHP script you specify does not have to have the extension .php. They can have any file name and extension.

  2. Run the

    PHP code directly on 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.


  1. ##Note:

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

  2. Provide the
  3. 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

    以上三种运行代码的方法不能同时使用。

    和所有的外壳应用程序一样,PHP 的二进制文件(php.exe 文件)及其运行的 PHP 脚本能够接受一系列的参数。PHP 没有限制传送给脚本程序的参数的个数(外壳程序对命令行的字符数有限制,但您通常都不会超过该限制)。传递给您脚本的参数可在全局变量 $argv 中获取。该数组中下标为零的成员为脚本的名称(当 PHP 代码来自标准输入获直接用 -r 参数以命令行方式运行时,该名称为“-”)。另外,全局变量 $argc 存有 $argv 数组中成员变量的个数(而非传送给脚本程序的参数的个数)。

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

    # 以下命令将不会运行 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

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

    #!/usr/bin/php
    <?php
        var_dump
    ($argv);
    ?>
    Copy after login
    <span style="color:rgb(0,0,0);"><span style="color:rgb(0,0,187);"></span></span>

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

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

    ---------------------------------------- --------------------------------Command options---------- ------------------------------------------

    Table 23-3. Command line options

    -hUsing this parameter, you can get the complete list of command line parameters and A brief description of what these parameters do.
    Option name Description
    -s

    Display source files with syntax highlighting.

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


    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 placement php .ini file directory, 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

    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 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 a convenient method for syntax checking of the specified PHP code. If successful, the No syntax errors detected in string 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 the internal parser error message, 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 This command line parameter will call the phpinfo() function and print out the result. If PHP is not working properly, we recommend that you execute the php -i command to see if there are any error messages 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.
    -r

    Use this parameter to run PHP code on the command line. You don't include the starting and ending identifiers of PHP ( and ?>), otherwise it will cause syntax parsing errors.


    Note: When using this form of PHP, special care should be taken to avoid conflict with the command line parameter substitution performed by the shell environment.

    Example showing syntax parsing errors

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

    The problem here is that even though double quotes " are used, sh/bash still performs parameter substitution. Because $foo is not defined. After being replaced, its position becomes a null character. Therefore, at runtime, the code actually read by PHP is:

    $ php -r " = get_defined_constants();"

    The correct way is to use single quotes '. In a string quoted with single quotes, variables will not be restored to their original values ​​by 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"]=> [...]

    If you are using a shell other than sh/bash, you may encounter other problems. Please report bugs you encounter or email phpdoc@lists.php.net.

    You may also encounter various problems when you try to introduce the shell's environment variables into the horse or use backslashes to escape characters. Please pay attention when using them!



    ##Note: -r is in CLI Valid in SAPI, invalid in CGI SAPI.


    PHP’s command line mode enables PHP scripts to run completely independently of the WEB server. If you are using a Unix system, you need to add a special line of code at the beginning of your PHP script to enable it to be executed, so that the system knows what program to use to run the script. Under the Windows platform, you can associate the double-click attributes of the
    php.exe and .php files, or you can write a batch file to execute the script using PHP. The first line of code added for Unix systems will not affect the running of the script under Windows, so you can also use this method to write cross-platform scripts. The following is an example of a simple PHP command line program.

    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. The immediate parameter is --help, -help, -h or -?, we still print out the help information and dynamically The name of the output script. 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:


    Example 23-1. PHP script (script.php) trying to run in command line mode#!/usr/bin/phpThis is a command line PHP script with one option. Usage:



    ##@c:\php\cli\php.exe script.php %1 %2 %3 %4


    The above is the detailed content of Command line execution under PHP. 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!