Php command line mode

Source: Internet
Author: User
Tags html header sapi perl script
PHP features: the command line mode starts with version 4.3.0. PHP provides a new type of cli sapi (Server Application Programming Interface, Server Application Programming Port) support, named CLI, command Line Interface, that is, Command Line Interface. As the name suggests, the cli sapi module is mainly used as a PHP development shell application. There are many differences between cli sapi and other cli sapi modules. we will elaborate in this chapter. It is worth mentioning that CLI and CGI are different SAPIs, although there are many common behaviors between them.

Cli sapi was first released with PHP 4.2.0, but it is still an experimental version. you need to add the -- enable-cli parameter when running./configure. Since PHP 4.3.0, cli sapi has become a formal module. the -- enable-cli parameter must be set to on by default. you can also use the -- disable-cli parameter to block it.

Starting from PHP 4.3.0, the name, location, and existence of the CLI/CGI binary execution file vary depending on the installation of PHP on the system. By default, when you run make, both CGI and CLI are compiled and placed in the sapi/cgi/PHP and sapi/cli/php directories of the php source file directory. Note that both files are named php. What happens during the make install process depends on the configuration line. If you select an SAPI module, for example, apxs, or the -- disable-cgi parameter, during the make install process, CLI will be copied to {PREFIX}/bin/php, unless CGI has been placed in that location. Therefore, for example, if there is -- with -- apxs in the configuration line, CLI will be copied to {PREFIX}/bin/php during the make install process. To cancel the installation of the CGI execution file, run make install-cli after make install. Alternatively, you can add the -- disable-cgi parameter in the configuration line.

Note:

Because -- enable-cli and -- enable-cgi are both valid by default, you do not need to add -- enable-cli in the configuration line to make the CLI copy 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 name of the CLI is a php-cli.exe, and php.exe in the same folder is CGI. Starting with PHP 4.3.0, the CLI execution file in the Windows release package is php.exe, which is placed in a separate folder named cli, namely cli/php.exe. In PHP 5, CLI exists in the main folder named php.exe, while the CGI version is named php-cgi.exe.

From PHP 5, a new file named php-win.exe is published with the package. It is equivalent to the CLI version, but php-win does not output any content, so it does not provide the console ("DOS window" is not displayed "). This method is similar to php-gtk. You need to configure it with the -- enable-cli-win32 option.

Note: How do I know which sapi I am using?

In the command line, run php-v to know whether the php is CGI or CLI. See the php_sapi_name () function and the constant PHP_SAPI.

Note:

The Unix man page is added to PHP 4.3.2. You can type man php in the command line to view it.

The following are the significant differences between cli sapi and other cli sapi modules:

Unlike cgi sapi, its output does not contain any header information. Although cgi sapi provides a method to cancel the HTTP header information, there is no similar method in cli sapi to enable the output of HTTP header information. CLI starts in quiet mode by default, but to ensure compatibility, The-q and -- no-header parameters are retained for backward compatibility, so that the old CGI script can be used. At runtime, 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 ). When an error occurs, the error message of plain text is output (not in HTML format ).

Cli sapi forcibly overwrites some settings in php. ini, because these settings are meaningless in the Shell environment.

Override php. ini settings

Set Options

Default value of CLI SAPI

Remarks

Html_errors FALSE the meaningless HTML tag will make the error information messy, so it is very difficult to read the error information in the shell. Therefore, change the default value of this option to FALSE.

Implicit_flush TRUE in command line mode, all outputs from print and echo are immediately written to the output end without any buffering operation. If you want to delay or control the standard output, you can still use the output buffering settings.

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

Register_argc_argv TRUE because it is set to TRUE, argc (number of parameters transferred to the application) and argv (arrays containing actual parameters) can always be accessed in cli sapi ). For PHP 4.3.0, when using cli sapi, the PHP variables $ argc and $ argv have been registered and set the corresponding values. In earlier versions, the establishment of these two variables in CGI or module versions depends on setting the PHP setting option register_globals to on. Besides 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 setting file php. ini or any specified other files. These default values are limited to change after all other settings files are parsed. However, their values can be changed during the running process (although these settings are meaningless for the running process ).

To reduce the work in the Shell environment, we define the following constants:

Dedicated CLI constants

Constant name

Description

STDIN an opened stream pointing to stdin. You can call the following method:

 

To read a row of content from stdin, use

 

STDOUT an opened stream pointing to stdout. You can call it as follows:

 

STDERR an opened stream pointing to stderr. You can call it as follows:

 

With the above constants, you do not need to create a stream pointing to stderr. you only need to simply use these constants to replace the stream pointing:

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

PHP will automatically complete these operations without shutting down these streams on its own.

Cli sapi does not change the current directory to the directory where the running script is located. The following example shows the differences between this module and the cgi sapi module:

 

When using CGI, the output is

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

Obviously, PHP changes the current directory to the directory where the script just run is located.

Use the cli sapi mode to obtain the following information:

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

This makes it very convenient to write shell tools using PHP.

Note:

You can add the-C parameter to the cgi sapi when running the command line to support the function of cli sapi.

The following are the option parameters of the command line mode provided by the PHP binary file (php.exe program). you can run the PHP command with the-h parameter to query these parameters at any time.

Usage: php [options] [-f] 
 
   [--] [args...]       php [options] -r 
   [--] [args...]       php [options] [-B 
   
    ] -R 
     [-E  ] [--] [args...] php [options] [-B  ] -F  [-E  ] [--] [args...] php [options] -- [args...] php [options] -a -a Run interactively -c  |  Look for php.ini file in this directory -n No php.ini file will be used -d foo[=bar] Define INI entry foo with value 'bar' -e Generate extended information for debugger/profiler -f  Parse  . -h This help -i PHP information -l Syntax check only (lint) -m Show compiled in modules -r  Run PHP  without using script tags  -B  Run PHP  before processing input lines -R  Run PHP  for every input line -F  Parse and execute  for every input line -E  Run PHP  after processing all input lines -H Hide any passed arguments from external tools. -s Display colour syntax highlighted source. -v Version number -w Display source with stripped comments and whitespace. -z  Load Zend extension  . args... Arguments passed to script. Use -- args when first argument starts with - or script is read from stdin                
   
 

The cli sapi module has the following three methods to obtain the PHP code to run:

Run the specified file in PHP.

php my_script.phpphp -f my_script.php

The above two methods (using or without the-f parameter) can run the given my_script.php file. You can choose to run any file. the specified PHP script does not have to use. php as the extension, and 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, pay attention to the substitution of shell variables and the use of quotation marks.

Note:

Please read the above example carefully. there is no start or end mark when running the code! After the-r parameter is added, these tokens are not required, and adding them will lead to syntax errors.

Provide the PHP code to be run through standard input (stdin. The above usage provides a very powerful function to dynamically generate PHP code and run the code through the command line, as shown in the following example:

$ some_application | some_filter | php | sort -u >final_output.txt

The preceding three methods for running code cannot be used at the same time.

Like all shell applications, PHP's binary file (php.exe file) and its running PHP script can accept a series of parameters. PHP does not limit the number of parameters transmitted to the script program (the shell program has a limit on the number of characters in the command line, but generally does not exceed this limit ). Parameters passed to the script can be obtained from the global variable $ argv. The member marked as zero in the array is the script name (this name is "-" when the PHP code comes from the standard input and runs directly using the-r parameter as a command line). In addition, the global variable $ argc contains the number of member variables in the $ argv array (instead of the number of parameters transmitted to the script program ).

As long as the parameters transmitted to the script do not start with A-symbol, you do not need to pay too much attention. Passing parameters starting with "-" to the script may cause errors, because PHP considers that it should handle these parameters by itself. You can use the parameter list separator -- to solve this problem. After PHP parses the parameters, all parameters after the symbol are transmitted to the script program as they are.

# The following command will not run the PHP code, but only show instructions for using the PHP command line mode: $ php-r 'Var _ dump ($ argv); '-hUsage: php [options] [-f]  [Args...] [...] # the following command transfers the "-h" parameter to the script program. PHP does not display the command line mode instructions: $ 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 use # in the first line #! Start with/usr/bin/php, add the normal PHP code containing the start and end tags of PHP, and set the correct running attributes for the File (for example: chmod + x test ). This method allows the file to be directly executed like a shell script or a PERL script.

#!/usr/bin/php 

If you change the file name to test and put it in the current directory, you can perform the following operations:

$ 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 can still run normally when a parameter starting with-is sent to the script.

Long options available since PHP 4.3.3:

Command line options

Option name

Long name

Description

-A -- interactive PHP running. If the Readline extension is added during PHP compilation (unavailable in Windows), a good shell will be obtained, including an automatic function (for example, when you enter a variable name, press the TAB key, and PHP will automatically complete the variable name) and Command History, which can be accessed by the up or down key. History exists ~ /. Php_history file.

Note:

Files contained in auto_prepend_file and auto_append_file will be parsed in this mode, but there are some restrictions. for example, a function must be defined before it is called.

-C -- php-ini with this parameter, you can specify a place for php. ini file directory, or directly specify a custom INI file (the 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 this option is not specified, PHP searches 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 with this parameter, you can set any configuration option values that can be set in the php. ini file. The syntax is:

-d configuration_directive[=value]

Example ):

# If the value is omitted, the configuration option is set to "1" $ php-d max_execution_time-r '$ foo = ini_get ("max_execution_time"); var_dump ($ foo ); 'string (1) "1" # The value is blank, the configuration option will be set to "" php-d max_execution_time =-R' $ foo = ini_get ("max_execution_time"); var_dump ($ foo); 'string (0) "" # The configuration option will be set to any value 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 -- profile-info activates the extended information mode and is used for debugging/testing.

-F -- file parses and runs the file name specified by the-f option. This parameter is optional and can be omitted. it only specifies the name of the file to be run.

-H and -? -- Help and -- usage use this parameter to obtain a complete list of command line parameters and a brief description of the functions of these parameters.

-I -- info this command line parameter calls the phpinfo () function and displays the result. If PHP does not work properly, we recommend that you run the php-I command to check whether any error information is output before or where the information table is located. Note that when CGI is used, the output content is in HTML format, so the output information is too large.

-L -- syntax-check: This parameter provides a convenient method to check the syntax of the specified PHP code. If successful, No syntax errors detected in is written to the standard output. String, and the shell return value is 0. If it fails, Errors parsing is output. And internal parser error messages to the standard output, and the shell return value is not set to 255. This parameter cannot check for fatal errors (for example, undefined functions). If you want to detect fatal errors, use the-f parameter.

Note:

This parameter cannot be used with-r.

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

$ php -m[PHP Modules]xmltokenizerstandardsessionposixpcreoverloadmysqlmbstringctype[Zend Modules]

-R -- run: this parameter can be used to run a single PHP code line in the command line. You do not need to add the start and end identifiers of PHP ( ). Otherwise, the syntax parsing error will occur.

Note:

When using PHP in this form, avoid conflict with the command line parameter replacement in the Shell environment.

Example of a syntax parsing error

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

The problem here is that even if double quotation marks are used, sh/bash still implements parameter replacement. Because $ foo is not defined, it is replaced with a null character, so the code actually read by PHP at runtime is:

$ php -r " = get_defined_constants();"

The correct method is to use single quotes '. In a single quoted string, the variable is not restored 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 the shell used is not sh/bash, more problems may occur. Please report bugs to» http://bugs.php.net. Note: When you try to use shell variables in code or use the backslash, it is still very easy to encounter problems.

Note:

-R is valid in cli sapi and invalid in cgi sapi.

Note:

This option is only used for basic purposes. Therefore, some configuration commands (such as auto_prepend_file and auto_append_file) are ignored in this mode.

-B -- process-begin: execute PHP code before processing stdin. PHP 5 is newly added.

-R -- process-code: execute PHP code for each input line. PHP 5 is newly added. In this mode, there are two special variables: $ argn and $ argi. $ Argn contains the row content currently processed by PHP, while $ argi contains the row number.

-F -- process-file: execute the PHP file for each input line. PHP 5 is newly added.

-E -- process-end: PHP code executed after the input is processed. PHP 5 is newly added. Use the-B,-R, and-E options to calculate the total number of rows of 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 displays the source code with syntax coloring. This parameter uses the internal creation mechanism to parse the file, generate an HTML highlighted version for it, and write the result to the standard output. Note that only one [...] Does not contain any HTML header.

Note:

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

-V -- version writes the version information of PHP, php sapi, and Zend to the 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 Technologies

-W -- strip shows the source code that removes comments and unnecessary spaces.

Note:

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

-Z -- zend-extension: load the Zend extension Library. If only one file name is given, PHP will try to extend the default path of the library from the current system (in Linux, this path is usually set by/etc/ld. so. specified by conf) to load the extension Library. If a file name is specified using an absolute path, the default path of the system Extension Library is not used. If the file name specified by the relative path is used, PHP only attempts to load the extension library in the relative directory of the current directory.

The PHP command line mode enables PHP scripts to run independently of web servers. If you use a Unix system, you need to add a special line of code at the beginning of the PHP script so that it can be executed, so that the system can know which program to use to run the script. On Windows, you can associate php.exe with the double-click attribute of the. php file, or compile a batch file to execute scripts in PHP. The first line of code added to the Unix system does not affect the running of the script in Windows. Therefore, you can use this method to compile a cross-platform scripting program. The following is an example of a simple PHP command line program.

Example #1 PHP script (script. php) that tries to run in command line mode)

#!/usr/bin/php This is a command line PHP script with one option. Usage:    can be some word you would like to print out. With the --help, -help, -h, or -? options, you can get this help. 

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

The preceding program checks whether the number of parameters is greater than 1 or less than 1. In addition, if the parameter is -- help,-help,-h, or -? And dynamically output the script name. If other parameters are received, display them.

If you want to run the above script in Unix, you need to make its attributes executable, and then simply run script. php echothis or script. php-h. In Windows, you can compile a batch file for this:

Example #2 run the PHP command line script (script. bat)

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

Assume that the above program is named script. php, and the php.exe file of the CLI version is placed in c: \ php \ cli \ php.exe. the batch processing file will help to pass additional parameters to the script program: 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.