Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
594 views
in Technique[技术] by (71.8m points)

pass parameters to php with shell

my question is probably easy to answer. i want to execute my php file with shell and pass parameters to it via shell example

php test.php parameter1 parameter2

is there a way to do that except using GET ?

thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Yes you can do it like that but you should reference the arguments from the $_SERVER['argv'] array. $_SERVER['argc'] will tell you how many args were received, should you want to use that as a first layer of validation to make sure a required number of args were input.

To illustrate this, running the following script as args.php arg1 arg2 arg3:

#!/usr/bin/php
<?php
var_dump($argv);
?>

will output:

array(4) {
  [0]=>
  string(8) "args.php"
  [1]=>
  string(4) "arg1"
  [2]=>
  string(4) "arg2"
  [3]=>
  string(4) "arg3"
}

Here is a practical example:

In this example, we'll create a script (days.php) that outputs the number of days since a particular date. It will accept 3 parameters, the month, day, and year as numbers.

#!/usr/bin/php
<?php
if($argc < 4 || !is_numeric($argv[1]) || !is_numeric($argv[2]) || !is_numeric($argv[3]))
{
    echo "Usage: $argv[0] mm dd yyyy
";
}
else
{
    $pastdate = mktime(0, 0, 0, $argv[1], $argv[2], $argv[3]);
    $diff = time() - $pastdate;
    $days = round($diff/60/60/24);
    echo "$days days since $argv[1]/$argv[2]/$argv[3]
";
}
?>

Shell call:

`$ ./days 11 17 1988` OR `php days.php 11 17 1988`

Output:

7699 days since 11/17/1988

Hope this helps.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...