pass parameters to php with shell

痞子三分冷 提交于 2019-11-28 07:32:44

问题


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


回答1:


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\n";
}
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]\n";
}
?>

Shell call:

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

Output:

7699 days since 11/17/1988

Hope this helps.




回答2:


You can use $argv to get the parameters.



来源:https://stackoverflow.com/questions/7803025/pass-parameters-to-php-with-shell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!