PHP command-line mode

Source: Internet
Author: User
Tags parse error sapi perl script
Starting with version 4.3.0, PHP provides a new type of CLI SAPI (Server application Programming Interface, service-side application programming port) support, called CLI, which means Command line Interface , which is the command-line interface. As the name implies, the CLI SAPI module is primarily used as a development shell application for PHP. There are many differences between the CLI SAPI and other CLI SAPI modules, which we will elaborate in this chapter. It is worth mentioning that the CLI and CGI are different SAPI, although there are many common behaviors between them.

The CLI SAPI was first released with PHP 4.2.0, but is still an experimental version and needs to be added with the--ENABLE-CLI parameter when running./configure. starting with PHP 4.3.0, the CLI SAPI becomes the formal module, the--ENABLE-CLI parameter is set to on by default, or it can be masked with parameter--disable-cli.

Starting with PHP 4.3.0, the filename, location, and presence of the cli/cgi binary executable file will vary depending on the installation of PHP on the system. By default, when you run make, both the CGI and the CLI are compiled and placed under sapi/cgi/php and sapi/cli/php in the PHP source file directory, respectively. It can be noted that two files are named for PHP. What happens during make install depends on the configuration line. If a SAPI module is selected at configuration time, such as APXS, or if the--disable-cgi parameter is used, the CLI will be copied to {prefix}/bin/php during make install, unless the CGI has been placed in that position. Therefore, for example, if there is--with--apxs in the configuration line, the CLI will be copied to {prefix}/bin/php during make install. If you want to undo the installation of the CGI execution file, run make install-cli after you install. Alternatively, you can add the--disable-cgi parameter to the configuration line.

Attention:

Since--enable-cli and--enable-cgi are also valid by default, it is not necessary to add--ENABLE-CLI to the configuration line to allow the CLI to be copied to {prefix}/bin/php during the make install process.

In the Windows release package between PHP 4.2.0 and PHP 4.2.3, the CLI file name is Php-cli.exe, and Php.exe under the same folder is CGI. starting with PHP 4.3.0, the executable file for the CLI in the Windows release package is Php.exe, placed under a separate folder called the CLI, which is cli/php.exe. In PHP 5, the CLI exists in the home folder, named Php.exe, and the CGI version is named Php-cgi.exe.

Starting with 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 any content and does not provide a console ("DOS window" will not pop up). This approach is similar to PHP-GTK. You need to use the--ENABLE-CLI-WIN32 option to configure it.

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

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

Note:

Added the Unix man page to PHP 4.3.2. You can view it by typing man php on the command line.

The following are notable differences compared to the CLI SAPI and other CLI SAPI modules:

Unlike CGI SAPI, its output has no header information. Although CGI SAPI provides a way to cancel the HTTP header information, there is no similar method in CLI SAPI to turn on the output of the HTTP header information. The CLI starts in quiet mode by default, but for compatibility, the-Q and--no-header parameters remain for backwards compatibility, making it possible to use old CGI scripts. At run time, the working directory is not changed to the current directory of the script (you can use the-C and--no-chdir parameters to be compatible with CGI mode). Error message (non-HTML format) for outputting plain text when an error occurs.

The CLI SAPI enforces some of the settings in the php.ini because these settings are meaningless in a shell environment.

overriding php.ini setting options

Setting options

CLI SAPI Default Value

Note

Html_errors FALSE HTML tags can make the error message messy, so it is very difficult to read the error message under the shell. Therefore, the default value of this option is changed to FALSE.

Implicit_flush TRUE in command-line mode, all output from print and Echo is immediately written to the output without any buffering operations. If you want to delay or control standard output, you can still use the output buffering setting.

Max_execution_time 0 (infinite value) given the infinite possibilities of using PHP in a shell environment, the maximum run time is set to infinity. Applications developed for the Web may run for only a few seconds, while Shell applications may run much longer.

REGISTER_ARGC_ARGV true because this setting is true, it is always possible to access the ARGC (the number of parameters passed to the application) and argv (an array containing the actual parameters) in the CLI SAPI. For PHP 4.3.0, when using CLI SAPI, the PHP variable $ARGC and $ARGV have been registered and the corresponding values have been set. In previous versions, the creation of these two variables in the CGI or module version depended on setting the PHP setup option register_globals to ON. In addition to the version and Register_globals settings, you can access them at any time by calling $_server or $HTTP _server_vars. 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 limited when all other settings files are parsed and changed. However, their values can be changed while the program is running (although these settings are meaningless for the running process).

To alleviate the work in the shell environment, we define the following constants:

CLI-specific constants

Constant name

Description

STDIN a stream that has an open point to STDIN. You can invoke the following methods:

<?php    $stdin = fopen (' Php://stdin ', ' R ');? >

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

<?php$line = Trim (fgets (STDIN)); Reads a row of fscanf from STDIN (STDIN, "%d\n", $number); Read digital?> from STDIN

STDOUT A stream that has an open point to STDOUT. It can be called as follows:

<?php    $stdout = fopen (' php://stdout ', ' w ');? >

STDERR a stream that has an open point to STDERR. It can be called as follows:

<?php       $stderr = fopen (' Php://stderr ', ' w ');? >

with these constants, you do not have to build a stream that points to such stderr, simply use these constants instead of the flow points:

Php-r ' fwrite (STDERR, "stderr\n");

Without having to shut down these streams yourself, PHP will do this automatically.

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

<?php    //A simple test program named test.php    Echo getcwd (), "\ n";? >

When using the CGI version, its output is

$ pwd/tmp$ php-cgi-f another_directory/test.php/tmp/another_directory

It is obvious that PHP has changed the current directory to the same directory as the script you just ran.

Using the CLI SAPI mode, you get:

$ pwd/tmp$ php-q another_directory/test.php/tmp

This makes it much easier to write shell tools with PHP.

Note:

You can add the-c parameter to the CGI SAPI at the command line, enabling it to support the functionality of the CLI SAPI.

The following is the option parameter for the command-line mode provided by the PHP binaries (that is, the Php.exe program), and you can run PHP commands with the-h parameter to query these parameters at any time.

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 would be used-d Foo[=bar] Define INI entry foo with value ' bar '-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 PA  ssed 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 was read from stdin

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.phpphp-f my_script.php

Both of these methods (with or without the-f parameter) are able to run a given my_script.php file. You can select any file to run, and the specified PHP script does not have to be in. php as an extension, they can have any file name and extension.

Run the PHP code directly on the command line.

Php-r ' Print_r (get_defined_constants ()); '

When using this method, be aware of the substitution of shell variables and the use of quotation marks.

Note:

Please read the above example carefully, there are no start and end tags when running the code! With the-r parameter, these tokens are not required, plus they cause syntax errors.

Provides PHP code that needs to be run through standard input (stdin). The above usage provides a very powerful feature that allows you to dynamically generate PHP code and run it from the command line, as shown in the following example:

$ some_application | Some_filter | php | Sort-u >final_output.txt

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

Like all shell applications, PHP binaries (php.exe files) and their PHP scripts can accept a range of parameters. PHP does not limit the number of parameters that are passed to the script (the shell has a limit on the number of characters on the command line, but it usually does not exceed the limit). The parameters passed to the script can be obtained in the global variable $ARGV. The name of the script whose members are labeled zero in the array is "-" when the PHP code comes from standard input and is run directly with the-R parameter on the command line. In addition, the global variable $ARGC the number of member variables in the $ARGV array (not the number of parameters passed to the script).

As long as the parameters passed to the script do not begin with the-sign, there is no need to pay too much attention. Passing a parameter to the script with a-start will result in an error, because PHP will assume that it should handle these parameters by itself. You can use the parameter list delimiter--to solve this problem. After parsing the parameters in PHP, all the parameters after the symbol are passed to the script as they are.

# The following command will not run PHP code, but only show instructions for using PHP command-line mode: $ Php-r ' var_dump ($argv); '-husage:php [options] [-f] <file> [args ...] [...] # The following command will pass the "-H" parameter to the script, and PHP will not show instructions for using the command line mode: $ Php-r ' var_dump ($ARGV); '---Harray (2) {  [0]=>  string (1) "-"  [1]=>  String (2) "-H"}

In addition, there is another way to use PHP for shell scripts. You can write a script and start with #!/usr/bin/php in the first line, followed by the normal PHP code that was included with the PHP start and end tags, and then set the correct run properties for the file (for example: chmod +x test). This method allows the file to be executed directly like a shell script or a PERL script.

#!/usr/bin/php<?php    var_dump ($ARGV);? >

If you change the file name to test and are placed in the current directory, you can do the following:

$ chmod +x test$./test-h--Fooarray (4) {  [0]=>  string (6) "./test"  [1]=>  string (2) "-H"  [2]= >  string (2) "--"  [3]=>  string (3) "Foo"}

As you can see, the script will still work correctly when you send the arguments that begin with-to the script.

Long options that are valid since PHP 4.3.3:

Command-Line Options

Option name

Long name

Description

-A--interactive interactively run PHP. If you compile PHP with the Readline extension (not available under Windows), you will get a good shell, including an auto-complete feature (for example, when you type a variable name, press the TAB key, PHP automatically completes the variable name), and the command history. You can use the up and down keys to access. The history exists in the ~/.php_history file.

Note:

Files contained by Auto_prepend_file and Auto_append_file are parsed in this mode, but some limitations, such as functions, must be defined before they are called.

- c--php-ini with 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

If you do not specify this option, PHP will search for files in the default location.

-N--no-php-ini completely ignores php.ini. This parameter is valid after PHP 4.3.0.

-D--define Use this parameter to set the value of any configuration option that can be set in the php.ini file, with the syntax:

-D Configuration_directive[=value]

Example (broken line display for layout reasons):

# The value portion is omitted and the configuration option will be set to "1" $ php-d max_execution_time-        r ' $foo = Ini_get ("Max_execution_time"); Var_dump ($foo); ' The value portion of string (1) "1" is blank, and the configuration option will be set to "php-d max_execution_time=-        r ' $foo = Ini_get (" Max_execution_time "); Var_dump ($foo); ' String (0) "" # configuration option will be set to the value after any ' = ' character $  php-d max_execution_time=20-        r ' $foo = Ini_get ("Max_execution_time"); Var_dump ($foo); ' String (2) "$" $  php-        d max_execution_time=doesntmakesense        -r ' $foo = Ini_get ("Max_execution_time"); var_ Dump ($foo); ' String ("Doesntmakesense")

-e--profile-info activates the extended information mode and is used for debugging/testing.

-F--file Parse and run the-F option given the file name. This parameter is optional and can be omitted to indicate only the file name that needs to be run.

-H and-? --help and--usage Use this parameter to get a complete list of command-line arguments and a simple description of the function of these parameters.

-I--info the command-line argument calls the Phpinfo () function and displays the result. If PHP is not working properly, it is recommended that you execute the php-i command to see if there is any error message output before or in the information table. Note that when using CGI, the output is in HTML format, so the output information is large.

-L--syntax-check This parameter provides a convenient way to check the syntax of the specified PHP code. If successful, writes NO syntax errors detected in <filename> string to the standard output, and the shell returns a value of 0. If it fails, the output Errors parsing <filename> and the internal parser error message to standard output, while the shell return value is not set to 255. This parameter will not be able to check for fatal errors (such as undefined functions), and if you also want to detect fatal errors, use the-f parameter.

Note:

This parameter cannot be used in conjunction with-R.

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

$ php-m[php modules]xmltokenizerstandardsessionposixpcreoverloadmysqlmbstringctype[zend Modules]

-R--run Use this parameter to run a single-line PHP code on the command line. There is no need to add PHP's start and end identifiers (<?php and?>), which will result in parsing errors.

Note:

When using this form of PHP, care should be taken to avoid conflicting command-line parameter substitutions with the shell environment.

Example of displaying syntax parsing errors

$ php-r "$foo = Get_defined_constants ();" Command Line Code (1): Parse error-parse error, unexpected ' = '

The problem here is that even with the use of double quotes, Sh/bash still implements the parameter substitution. Since the $foo is not defined, it is replaced with a null character in its place, so at run time, the code actually read by PHP is:

$ php-r "= Get_defined_constants ();"

The correct way is to use single quotes '. In a string quoted in single quotation marks, the variable is not reverted to its original value 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 that is not sh/bash, you may encounter more problems. Please report the Bug you have encountered to»http://bugs.php.net/. Note that it is still easy to run into problems when trying to use shell variables in code or using backslashes.

Note:

-R is valid in the CLI SAPI and is not valid in CGI SAPI.

Note:

This option is for very basic purposes only. Therefore, some configuration directives (such as Auto_prepend_file and Auto_append_file) are ignored in this mode.

-B--process-begin executes the PHP code before processing the stdin. PHP 5 new Plus.

-R--process-code executes PHP code for each input line. PHP 5 new Plus. There are two special variables in this mode: $argn and $argi. $argn contains the line content that PHP is currently working on, and the $argi contains that line number.

-F--process-file executes PHP files for each input line. PHP 5 new Plus.

-e--process-end The PHP code that executes after the input is processed. PHP 5 new Plus. Use the-B,-R and-e options to calculate an example of the Total row count for a project.

$ Find My_proj | Php-b ' $l =0; '-r ' $l + = count (@file ($ARGN)); '-E ' echo "total Lines: $l \ n"; Total lines:37328

-S--syntax-highlight and--syntax-highlight display the source code with syntax highlighting color. This parameter uses the built-in mechanism to parse the file and generate an HTML-highlighted version of it and write the results to standard output. Note that the process has only generated a block of HTML markup for <code> [...] </code>, and does not contain any HTML headers.

Note:

This option cannot be used in conjunction with the-R parameter.

-V--version writes php,php SAPI and Zend version information to standard output. For example:

$ php-vphp 4.3.0 (CLI), Copyright (c) 1997-2002 the PHP groupzend Engine v1.3.0, Copyright (c) 1998-2002 Zend Technologie S

-W--strip shows the source code that removed the comments and extra whitespace.

Note:

This option cannot be used in conjunction with the-R parameter.

-Z--zend-extension load zend Extension library. Given only one file name, PHP will attempt to load the extension library from the default path of the current system extension library (which is typically specified by/etc/ld.so.conf under the Linux system). If you specify a file name with an absolute path, the system's extended library default path is not used. If the file name is specified with a relative path, PHP only attempts to load the extension library in the relative directory of the current directory.

PHP's command-line mode allows PHP scripts to be run independently of the Web server. If you use a Unix system, you need to add a special line of code to the front of the PHP script so that it can be executed so that the system knows which program to run the script. You can associate the double-click properties of the Php.exe and. php files under the Windows platform, or you can write a batch file to execute the script in PHP. The first line of code added for Unix systems does not affect the script running under Windows, so you can also use this method to write cross-platform scripting programs. The following is an example of a simple PHP command-line program.

Example #1 PHP script that tries to run as a command line (script.php)

#!/usr/bin/php<?phpif ($ARGC! = 2 | | in_array ($ARGV [1], Array ('--help ', '-help ', '-h ', '-? '))) {? >this is a command line, PHP script with one option.  Usage:  <?php echo $argv [0];?> <option>  <option> can be some word your would like to  print OU T. With the--HELP,-help,-H,  or-? options, can get this help.<?php} else {    echo $argv [1];}? >

In the above script, the first line of special code is used to indicate that the file should be executed by PHP. The version of the CLI is used here, so there will be no HTTP header information output. When writing a command-line application in PHP, you can use two parameters: $ARGC and $argv. The previous value is an integer that is 1 larger than the number of arguments (the name of the running script itself is also treated as a parameter). The second is an array containing parameters whose first element is the name of the script and the subscript is the number 0 ($argv [0]).

The above procedure checks whether the number of parameters is greater than 1 or less than 1. Also if the parameter is--help,-help,-H or-? , print out the Help information and dynamically output the name of the script at the same time. If you also receive additional parameters, display them.

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

Example #2 Batch file (Script.bat) that runs the PHP command-line script

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

Assuming that the above program is named Script.php, and that the CLI version of the Php.exe file is placed in C:\php\cli\php.exe, the batch file will help pass the additional parameters to the script: Script.bat echothis or Script.bat- H.

  • Related Article

    E-Commerce Solutions

    Leverage the same tools powering the Alibaba Ecosystem

    Learn more >

    Apsara Conference 2019

    The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

    Learn more >

    Alibaba Cloud Free Trial

    Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

    Learn more >

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.