The command line execution in PHP is the option parameters provided by the command line mode file (namely, the php.exe program). you can query these parameters through the PHP-h command at any time. Usage: php [options] [-f] & lt; file & gt; [command line execution in PHP
Below is PHPBinary File (that is Php.exeProgram ).
PHP-hCommand to query these parameters.
Usage: php [options] [-f]
[args...] php [options] -r
[args...] php [options] [-- args...] -s Display colour syntax highlighted source. -w Display source with stripped comments and whitespace. -f
Parse
. -v Version number -c
|
Look for php.ini file in this directory -a Run interactively -d foo[=bar] Define INI entry foo with value 'bar' -e Generate extended information for debugger/profiler -z
Load Zend extension
. -l Syntax check only (lint) -m Show compiled in modules -i PHP information -r
Run PHP 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
|
CLI SAPIThe module has the following three methods to obtainPHPCode:
?
?
In windows, use double quotation marks as much as possible. in linux, use single quotation marks as much as possible.
LetPHPRun the specified file.
php my_script.php php -f "my_script.php" |
The above two methods (use or not use-FParameters) can run the specifiedMy_script.phpFile. You can select any file to run.PHPThe script is not required. PhpIs the extension, they can have any file name and extension.
Run the command linePHPCode.
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! Add-RAfter parameters, these tokens are not required. adding them will cause syntax errors.
Pass standard input (Stdin) ProvidePHPCode.
The above usage provides us with very powerful functions, so that we can dynamically generatePHPCode and run the code through the command line:
$ 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,PHPBinary file (Php.exeFile) and its runningPHPThe script can accept a series of parameters.PHPThere is no limit on the number of parameters transferred to the script program (the shell has a limit on the number of characters in the command line, but you generally do not exceed this limit ). The parameters passed to your script can be found in global variables.$ Argv. In this array, the member marked as zero is the name of the script (whenPHPThe code is directly used for standard input.-RThis parameter is named"-"). In addition, global variables$ ArgcExist$ ArgvNumber of member variables in the array (rather than the number of parameters transferred to the script program ).
As long as the parameter you send to your script is not-You do not need to pay too much attention to it. Send to your script-Parameters startingPHPIt is deemed that these parameters should be processed by itself. You can use the parameter list separator--To solve this problem. InPHPAfter the parameters are parsed, all parameters after the symbol are transmitted to your 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, we have another wayPHPUsed for shell scripts. You can write a script and#! /Usr/bin/phpStartPHPThe start and end tags contain normalPHPCode, and then set the correct running attribute for the file. This method allows the file to be directly executed like a shell script or a PERL script.
#!/usr/bin/php ????var_dump($argv); ?> |
Assume that the file name is changedTestAnd put it in the current directory. we can do the following:
$ chmod 755 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.
?
?
?
?
?
?
------------------------------------------ Command options -----------------------------------------------------
?
Table 23-3. command line options
Option name description
-S |
Displays source files with syntax highlighted colors. This parameter uses the internal creation mechanism to parse the file and generateHTMLHighlight the version and write the result to the standard output. Note that only one [...] OfHTMLIt does not contain anyHTMLHeader.
Note:This option cannot match-RParameters are used at the same time.
|
-W |
Displays the source code without comments and spaces.
Note:This option cannot match-RParameters are used at the same time.
|
-F |
Parse and run the given file name. This parameter is optional and can be left unspecified. it only specifies the name of the file to be run. |
-V |
Standard output of writing PHP, php sapi, and Zend version information. For example:
$ php -vPHP 4.3.0-dev (cli), Copyright (c) 1997-2002 The PHP GroupZend Engine v1.3.0, Copyright (c) 1998-2002 Zend Technologies |
|
-C |
With this parameter, you can specifyPhp. iniFile directory, or directly specify a customINIFile, the file name can bePhp. ini. For example:
$ php -c /custom/directory/ my_script.php $ php -c /custom/directory/custom-file.ini my_script.php |
|
- |
Run PHP interactively. |
-D |
You can set this parameter by yourself.Php. iniSet the variable value in the file. Its 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 extension information for the debugger. |
-Z |
Load the Zend Extension Library. If only one file name is given, PHP will try to extend the default path of the library from your system (in Linux, this path is usually/Etc/ld. so. confSpecified) load the extension Library. If you specify a file name using an absolute path, the default path of the System Extension library will not be used. If the file name specified by the relative path is used, PHP only attempts to load the extension Library relative to the current directory. |
-L |
This parameter providesPHPA convenient method for checking the code syntax. If successful, the data is written to the standard output.No syntax errors detected in String, and the shell return value is0. If it failsErrors parsing And the internal parser error information will be written to the standard output together, and the shell return value will not be set255. This parameter will not be able to check for fatal errors (such as undefined functions). If you want to detect a name error, use-FParameters.
Note:This parameter cannot be-R.
|
-M |
With this parameter, PHP prints out the built-in and loaded PHP and Zend modules:
$ php -m[PHP Modules]xmltokenizerstandardsessionposixpcreoverloadmysqlmbstringctype [Zend Modules] |
|
-I |
This command line parameter is calledPhpinfo ()Function and print the result. IfPHPNot working properly. we recommend that you executePhp-ICommand to check whether any error information is output before or in the information table. Note that the output content isHTMLFormat, so the output information is too long. |
-R |
You can run this parameter on the command line.PHPCode. YouNoAddPHPStart and end identifiers ( And?>). Otherwise, the syntax parsing error will occur.
Note:This formPHPAvoid 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 double quotation marks are used instantly.", Sh/bash still implements parameter replacement. Because$ FooIt is not defined. after it is replaced, its location becomes a null character, so it is actuallyPHPThe read code 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 you use is not sh/bash, you may encounter other problems. Report your bugs or send an email to The phpdoc@lists.php.net.
When you try to introduce the environment variable of the shell to a horse or escape characters with a backslash, you may also encounter various problems. please pay attention when using it!
Note:-RInCLIValid in SAPICGIInvalid SAPI.
|
-H |
With this parameter, you can get a complete list of command line parameters and a brief description of the functions of these parameters. |
?
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 your PHP script so that it can be executed, in this way, the system will know what program to use to run the script. On Windows, you canPhp.exeAnd. PhpDouble-click properties of the file are associated. you can also write a batch file to execute the script 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 23-1. PHP script (script. php)
#!/usr/bin/php if ($argc != 2 || in_array($argv[1], array('--help', '-help', '-h', '-?'))) { ?>
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.
} else { ????echo $argv[1]; } ?> |
|
In the above script, we use the first line of special code to indicate that the file should be executed by PHP. We use the CLI version here, so there is no HTTP header output. When you write a command line application in PHP, you can use two parameters:$ ArgcAnd$ 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 element contains an array with parameters. The first element is the script name and the subscript is 0 ($ Argv [0]).
In the above program, we checked whether the number of parameters is greater than 1 or less than 1. The real-time parameter is-- Help,-Help,-HOr-?, We still print the help information and dynamically output the script name. If other parameters are received, we can also display them.
If you want to run the above script in Unix, you need to make it executable script, and then simply runScript. php echothisOrScript. php-h. In Windows, you can write a batch file for this:
@c:\php\cli\php.exe script.php %1 %2 %3 %4 |
|