使用shell将参数传递给php [英] pass parameters to php with shell
问题描述
我的问题可能很容易回答.我想用外壳执行我的php文件,并通过外壳将参数传递给它 例子
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
除了使用GET之外,还有其他方法吗?
is there a way to do that except using GET ?
谢谢
推荐答案
是的,您可以这样做,但是您应该引用$_SERVER['argv']
数组中的参数. $_SERVER['argc']
会告诉您收到了多少个参数,如果您想将其用作验证的第一层,以确保输入了所需数量的参数.
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.
为了说明这一点,请以args.php arg1 arg2 arg3
身份运行以下脚本:
To illustrate this, running the following script as args.php arg1 arg2 arg3
:
#!/usr/bin/php
<?php
var_dump($argv);
?>
将输出:
array(4) {
[0]=>
string(8) "args.php"
[1]=>
string(4) "arg1"
[2]=>
string(4) "arg2"
[3]=>
string(4) "arg3"
}
这是一个实际的例子:
在此示例中,我们将创建一个脚本(days.php),该脚本输出自特定日期以来的天数.它将接受3个参数,分别是月,日和年.
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调用:
`$ ./days 11 17 1988` OR `php days.php 11 17 1988`
输出:
7699 days since 11/17/1988
希望这会有所帮助.
这篇关于使用shell将参数传递给php的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!