Three Ways for PHP Command Line Scripts to Receive Incoming Parameters

  • 2021-07-13 04:52:00
  • OfStack

Usually, PHP is requested in http mode, and parameters can be received in GET, or and POST mode. Sometimes, PHP needs to be executed as a script under shell command, such as timing tasks. This involves how to pass parameters to php under shell command. There are usually three ways to pass parameters.
1. Receive with the $argv or $argc parameter


<?php
/**
 * Use $argc $argv Acceptance parameter
 */
 
echo " Received {$argc} Parameters ";
print_r($argv);

Execute

[root@DELL113 lee]# /usr/local/php/bin/php test.php
Received 1 Parameters Array
(
    [0] => test.php
)
[root@DELL113 lee]# /usr/local/php/bin/php test.php a b c d
Received 5 Parameters Array
(
    [0] => test.php
    [1] => a
    [2] => b
    [3] => c
    [4] => d
)
[root@DELL113 lee]#

2. Use the getopt function

<?php
/**
 * Use getopt Function
 */
 
$param_arr = getopt('a:b:');
print_r($param_arr);

Execute

[root@DELL113 lee]# /usr/local/php/bin/php test.php -a 345
Array
(
    [a] => 345
)
[root@DELL113 lee]# /usr/local/php/bin/php test.php -a 345 -b 12q3
Array
(
    [a] => 345
    [b] => 12q3
)
[root@DELL113 lee]# /usr/local/php/bin/php test.php -a 345 -b 12q3 -e 3322ff
Array
(
    [a] => 345
    [b] => 12q3
)

3. Prompt the user for input

<?php
/**
 * Prompt the user for input, similar to Python
 */
fwrite(STDOUT,' Please enter your blog name: ');
echo ' The information you entered is: '.fgets(STDIN);

Execute

[root@DELL113 lee]# /usr/local/php/bin/php test.php

Please enter your blog name: this site www. ofstack. com
The information you entered is: this site www. ofstack. com
You can also do this without letting users enter empty information

<?php
/**
 * Prompt the user for input, similar to Python
 */
 
$fs = true;
 
do{
oif($fs){
fwrite(STDOUT,' Please enter your blog name: ');
$fs = false;
}else{
fwrite(STDOUT,' Sorry, the blog name cannot be empty, please re-enter your blog name: ');
}
 
$name = trim(fgets(STDIN));
 
}while(!$name);
 
echo ' The information you entered is: '.$name."\r\n";

Execute

[root@DELL113 lee]# /usr/local/php/bin/php test.php
Please enter your blog name:
Sorry, the blog name cannot be empty, please re-enter your blog name: Script Home
The information you entered is: Script Home


Related articles: