Pass parameters to PHP by shell commands

My computer develop environment

1
2
$ php -v
PHP 7.0.26

Using $argv or $argc

$argv is an array that includes parameters
$argc is the number of parameters

1
2
3
<?php
echo "total parameters count : {$argc}" . PHP_EOL;
print_r($argv);
1
2
3
4
5
6
7
8
9
10
$ php test.php name liyuliang age 25
total parameters count : 5
Array
(
[0] => test1.php
[1] => name
[2] => liyuliang
[3] => age
[4] => 25
)

Using function getopt

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?php
$shortopts = "";
$shortopts .= "f:"; // Required value
$shortopts .= "v::"; // Optional value
$shortopts .= "abc"; // These options do not accept values

$longopts = [
"required:", // Required value
"optional::", // Optional value
"option", // No value
"opt", // No value
];

$options = getopt($shortopts, $longopts);
print_r($options);
1
2
3
4
5
6
7
8
9
$ php test.php -f "value for f" -v -a --required value --optional="optional value"
Array
(
[f] => value for f
[v] =>
[a] =>
[required] => value
[optional] => optional value
)

Using STDOUT

1
2
3
4
<?php
fwrite(STDOUT, 'What is your name:');
$name = trim(fgets(STDIN));
echo "Welcome ! {$name} " . PHP_EOL;
1
2
3
$ php test.php 
What is your name:liyuliang
Welcome ! liyuliang
Share