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 common http requests in PHP. you can use GET or POST to receive parameters, sometimes PHP needs to be executed as a script under shell commands, such as scheduled tasks. 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
The code is as follows:
<? Php
/**
* Use $ argc $ argv to accept parameters
*/
Echo "received {$ argc} Parameters ";
Print_r ($ argv );
Run
The code is as follows:
[Root @ DELL113 lee] #/usr/local/php/bin/php test. php
1 parameter Array received
(
[0] => test. php
)
[Root @ DELL113 lee] #/usr/local/php/bin/php test. php a B c d
Five parameter arrays are received.
(
[0] => test. php
[1] =>
[2] => B
[3] => c
[4] => d
)
[Root @ DELL113 lee] #
II. use the getopt function
The code is as follows:
<? Php
/**
* Use the getopt function
*/
$ Param_arr = getopt ('A: B :');
Print_r ($ param_arr );
Run
The code is as follows:
[Root @ DELL113 lee] #/usr/local/php/bin/php test. php-a 345
Array
(
[A] = & gt; 345
)
[Root @ DELL113 lee] #/usr/local/php/bin/php test. php-a 345-B 12q3
Array
(
[A] = & gt; 345
[B] => 12q3
)
[Root @ DELL113 lee] #/usr/local/php/bin/php test. php-a 345-B 12q3-e 3322ff
Array
(
[A] = & gt; 345
[B] => 12q3
)
3. prompt user input
The code is as follows:
<? Php
/**
* Prompt user input, similar to Python
*/
Fwrite (STDOUT, 'Enter your blog name :');
Echo 'the information you entered is: '. fgets (STDIN );
Run
The code is as follows:
[Root @ DELL113 lee] #/usr/local/php/bin/php test. php
Enter your blog name: www.bitsCN.com
The information you entered is: www.bitsCN.com
You can do the same without entering blank information.
The code is as follows:
<? Php
/**
* Prompt user input, similar to Python
*/
$ Fs = true;
Do {
Oif ($ fs ){
Fwrite (STDOUT, 'Enter your blog name :');
$ Fs = false;
} Else {
Fwrite (STDOUT, 'Sorry, the blog name cannot be blank. Please enter your blog name again :');
}
$ Name = trim (fgets (STDIN ));
} While (! $ Name );
Echo 'the information you entered is: '. $ name. "\ r \ n ";
Run
The code is as follows:
[Root @ DELL113 lee] #/usr/local/php/bin/php test. php
Enter your blog name:
Sorry, the blog name cannot be blank. Please enter your blog name again:
The information you entered is: