PHP command line to perform a detailed

Source: Internet
Author: User
Tags parse error sapi perl script zend

The following are the options parameters for the command-line mode provided by the PHP binaries (that is, the Php.exe program), which you can query at any time by using 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 ' Bar '
-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--the args when first argument
Starts With-or script is read from stdin

The CLI SAPI module has the following three different ways to get the PHP code you want to run:

In a Windows environment, use double quotes as much as possible, and use single quotes as much as possible in a Linux environment.

  1. Let PHP run the specified file.

    /table>
    php my_script.php 
    Php-f "my_script.php"
  2. php-r "Print_r (Get_defined_constants ());" 

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

  3. Provides PHP code that needs to be run through standard input (stdin).

    The above usage provides us with a very powerful feature that allows us to dynamically generate PHP code and run it from the command line, as shown in the example below:

    $ 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 you typically do not exceed that limit). The parameters passed to your 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 you send to your script do not begin with a-sign, you do not need to pay too much attention. Sending a parameter to your script with a-start will cause 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 will be passed to your script as is.

# The following command will not run PHP code, but only show instructions for using PHP command line mode:
$ Php-r ' var_dump ($ARGV); '-H
usage: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);"---H
Array (2) {
[0]=>
String (1) "-"
[1]=>
String (2) "-H"
}

In addition, we have another way to use PHP for Shell scripting. 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. This method allows the file to be executed directly like a shell script or a PERL script.

#!/usr/bin/php
<?php
Var_dump ($a

RGV);
?>

Assuming that the file name is test and placed in the current directory, we can do the following:

$ chmod 755 Test
$./test-h--Foo
Array (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.

Table 23-3. Command-Line Options

Option Name Description
-S

Displays the source file with the 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 this process only generates an <code> [...] </code> HTML tag block, and does not contain any HTML headers.

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

-W

Displays the source code with comments and spaces removed.

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

-F

Parses and runs the given file name. This parameter is optional and can be added without specifying only the file name that needs to be run.

-v

$ php-vphp 4.3.0-dev (CLI), Copyright (c) 1997-2002 the PHP groupzend engin E v1.3.0, Copyright (c) 1998-2002 Zend Technologies
-C

With this parameter, you can specify a directory where the php.ini file is placed, or 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

To run PHP interactively.

-D

Use this parameter to set the value of the variable in the php.ini file itself, with the syntax:

- D Configuration_directive[=value]

Example:

# ommiting the value part would set the given configuration directive to "1" $ php-d max_exe Cution_time-r ' $foo = Ini_get ("Max_execution_time"); Var_dump ($foo); ' String (1) "1" # Passing a empty value part would 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 would be set to anything passed after the ' = ' character$ php-d max_execution_ti Me=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

Generates extended information for the debugger, and so on.

-Z

Load the Zend extension library. Given only one file name, PHP will attempt to load the extension library from the default path of your 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 default path of the system's extension library will not be used. If the file name is specified with a relative path, PHP only attempts to load the extension library relative to the current directory.

-l

Note: This parameter cannot be used with-R.

-M

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

$ php-m[php Modules]xmltokenizerstandardsessionposixpcreoverloadmysqlmbstringctype [Zend Modules]
-I. The command-line argument calls the Phpinfo () function and prints out the result. If PHP is not working properly, we recommend that you execute the php-i command to see if there is any error message output before or in the information table. Note that the output is in HTML format, so the output information is large.
-R

Use this parameter to run PHP code at the command line. You do not need to add PHP's start and end identifiers (<?php and?>), or you will cause parsing errors.

Note: When using this form of PHP, you should be careful 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 the instant 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_defi

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 "]=> [...]

If you are using a shell other than Sh/bash, you may encounter other problems. Please report the bug you encountered, or send an email to phpdoc@lists.php.net.

When you try to introduce an environment variable from a shell to a horse or use a backslash to escape a character, you may encounter a variety of problems, please be careful when you use it!

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

-H With this parameter, you can get a complete list of command-line arguments and a simple description of the effects of these parameters.


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 your PHP script so that it can be executed so that the system knows what program to run the script with. Under the Windows platform you can associate the double-click properties of the Php.exe and. php files, or you can write a batch file to execute the script in PHP. The first line of code added to the Unix system does not affect the script running under Windows, so you can also use this method to write a cross-platform scripting program. The following is an example of a simple PHP command-line program.

example 23-1. PHP script that tries to run as 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 is some word you would like to print out. With the--help,-help,-H, or-? Options, can get this help.<?php} 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 are using the CLI version here, so there will be no HTTP header information output. When you write 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 one contains an array of arguments, the first element of which is the name of the script, and the subscript is the number 0 ($argv [0]).

In the above procedure we have checked whether the number of parameters is greater than 1 or less than 1. The immediate parameters are--help,-help,-H or-?, and we still print out the Help information and dynamically output the name of the 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:

Related recommendations:

Method of executing a PHP script with parameters and obtaining parameters based on the command line

Method of executing PHP script with parameters based on command line and getting parameters, PHP script _php tutorial

command line execution on PHP

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.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.