command line execution on PHP

Source: Internet
Author: User
Tags parse error sapi perl script
Command-line execution under PHP

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]
     
      
        [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 ' B Ar '-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 was 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.

    Php-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 php scripts You specify do not have to be in . PHP as extensions, they can have arbitrary filenames and extensions.

  2. Run the PHP code directly on the command line.

    Php-r "Print_r (Get_defined_constants ());

    When using this method, you should pay attention to the substitution of the shell variables and the use of quotation marks.

    Note: Please read the above example carefully, when running the code without the start and end of the marker! 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); '-husage:php [options] [-f] 
     
     
      
       [args ...] [...] # The following command will pass the "-H" parameter to the script, and PHP will not show instructions for using command-line mode: $ php-r "var_dump ($ARGV);"---Harray (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
????var_dump($argv);
?>

Assuming that the file name is test and placed 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 will still work correctly when you send the arguments that begin with - to the script.

?

?

?

?

?

?

------------------------------------------Command Options-----------------------------------------------------

?

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 the procedure does only generate an [...] 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

Standard output that writes the version information of PHP, PHP SAPI, and Zend. 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 Technol Ogies
-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_execution_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_executio N_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

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

This parameter provides a convenient way to check the syntax of the specified PHP code. If successful, writes the No syntax errors detected in string to the standard output, and the shell returns a value of 0. If it fails, the Errors parsing and internal parser error messages are written to standard output together with the shell return value set to 255.

This parameter will not be able to check for fatal errors, such as undefined functions, and if you want to detect errors, use the- F parameter.

Note: This parameter cannot be used in conjunction 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 ( and ?>), otherwise 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_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 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 attempts to run as a command line (script.php)

#!/usr/bin/php

if ($ARGC!= 2|| In_array($argv[1], Array ('--help ', '-help ', '-H ', '-?'))) {
?>

A command line, PHP script with one option.

?? Usage:
?? Echo $argv [0]; ?>

??Can be some word your would like
?? To print out. With the--help,-help,-H,
?? Or-? Options, you can get the 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 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:


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

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