Three methods for receiving input parameters in PHP command line scripts
This article mainly introduces three methods for receiving input parameters through PHP Command Line scripts, that is, using PHP scripts like Python scripts, Ruby scripts, and Shell scripts to process command line programs, for more information about how to obtain parameters in the command line, see.
PHP usually performs http requests. You can use GET or POST to receive parameters. Sometimes, you need to run PHP as a script under the shell command, such as a scheduled task. This involves how to pass Parameters to php under shell commands. There are usually three methods for passing parameters.
1. Use the $ argv or $ argc parameter to receive
<? Php/*** use $ argc $ argv to accept parameters */echo "receive {$ argc} Parameters"; print_r ($ argv );
Run
[Root @ phpernote lee] #/usr/local/php/bin/php test. php
1 parameter Array received
(
[0] => test. php
)
[Root @ phpernote lee] #/usr/local/php/bin/php test. php www phpernote com
Four parameter arrays are received.
(
[0] => test. php
[1] => www
[2] => phpernote
[3] => com
)
Ii. Use the getopt Function
Note: getopt only accepts parameters with the specified name.
<? Php/*** use the getopt function */$ param_arr = getopt ('name: age: '); // only the print_r ($ param_arr) parameters of name and age are accepted );
Run
[Root @ phpernote lee] #/usr/local/php/bin/php test. php-name jim
Array
(
[Name] => jim
)
[Root @ phpernote lee] #/usr/local/php/bin/php test. php-name jim-age 30
Array
(
[Name] => jim
[Age] => 30
)
[Root @ phpernote lee] #/usr/local/php/bin/php test. php-name jim-age 30-sex man
Array
(
[Name] => jim
[Age] => 30
)
Iii. Define CLI constants through the php system: STDIN, STDOUT, STDERR
<? Php $ fs = true; $ username = ''; do {if ($ fs) {fwrite (STDOUT, 'Enter the User name: '); $ fs = false ;} else {fwrite (STDOUT, 'sorry, the user name cannot be blank. Enter');} $ username = trim (fgets (STDIN);} while (! $ Username); echo 'the user name you entered is: '. $ username. "\ r \ n ";
Run
[Root @ phpernote lee] #/usr/local/php/bin/php test. php
Enter the User Name:
Sorry, the user name cannot be blank. Please enter Sun Wukong again
The user name you entered is Sun Wukong.