使用shell向php传递参数

发布于 2024-12-10 21:05:03 字数 169 浏览 5 评论 0原文

我的问题可能很容易回答。我想用 shell 执行我的 php 文件并通过 shell 将参数传递给它 例如,

php test.php parameter1 parameter2

除了使用 GET 之外,还有其他方法可以做到这一点吗?

谢谢

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

雪化雨蝶 2024-12-17 21:05:03

是的,您可以这样做,但您应该引用 $_SERVER['argv'] 数组中的参数。 $_SERVER['argc'] 将告诉您收到了多少个参数,如果您想将其用作第一层验证以确保输入所需数量的参数。

为了说明这一点,运行以下脚本 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 个参数,即数字形式的月、日和年。

#!/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

希望这有帮助。

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.

牛↙奶布丁 2024-12-17 21:05:03

您可以使用 $argv 来获取参数。

You can use $argv to get the parameters.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文