Home  >  Article  >  Backend Development  >  How to pass parameters to php script

How to pass parameters to php script

(*-*)浩
(*-*)浩Original
2019-09-10 14:52:334702browse

How to pass parameters to php script

Method 1 uses argc, argv

$argc — the number of parameters passed to the script

$argv — passed to Parameter array of the script

 1){  
        print_r($argv);  
    }

Run /usr/local/php/bin/php ./getopt.php -f 123 -g 456 under the command line (recommended learning: PHP programming from entry to proficiency )

# /usr/local/php/bin/php ./getopt.php -f 123 -g 456  
Array  
(  
    [0] => ./getopt.php  
    [1] => -f  
    [2] => 123  
    [3] => -g  
    [4] => 456  
)

Method 2 uses getopt function ()

array getopt ( string options[,arrayoptions[,arraylongopts [, int &$optind ]] )

Parameter analysis:

options

The string Each character in will be treated as an option character, and options matching the incoming script begin with a single hyphen (-). For example, an option string "x" identifies an option -x. Only a-z, A-Z and 0-9 are allowed.

longopts

Option array. Each element in this array will be treated as an options string, matching the options passed to the script with two hyphens (–). For example, the long option element "opt" identifies an option -opt.

options may contain the following elements:

单独的字符(不接受值)
后面跟随冒号的字符(此选项需要值)
后面跟随两个冒号的字符(此选项的值可选)
$options = "f:g:";  
$opts = getopt( $options );  
print_r($opts);   
php ./getopt.php -f 123 -g 456
运行结果:

Array  
(  
    [f] => 123  
    [g] => 456  
)

Method 3 Prompts the user for input, and then obtains the input parameters. A bit like C language

fwrite(STDOUT, "Enter your name: ");  
$name = trim(fgets(STDIN));  
fwrite(STDOUT, "Hello, $name!");

stdout – standard output device (printf(“..”)) is the same as stdout.

stderr - standard error output device

Both output to the screen by default.

But if you use the standard output to a disk file, you can see the difference between the two. stdout is output to a disk file and stderr is to the screen.

Run /usr/local/php/bin/php ./getopt.php from the command line

Run results

Enter your name: zhang //(zhang 为用户输入)  
Hello, zhang!

The above is the detailed content of How to pass parameters to php script. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:How to write php programNext article:How to write php program