从命令行运行带有变量的php脚本

时间:2009-06-10 08:38:21

标签: php command-line

我想从命令行运行PHP脚本,但我也想为该脚本设置一个变量。

浏览器版本:script.php?var=3

命令行:php -f script.php(但我如何给它包含3的变量?)

5 个答案:

答案 0 :(得分:35)

<强>脚本:

<?php

// number of arguments passed to the script
var_dump($argc);

// the arguments as an array. first argument is always the script name
var_dump($argv);

<强>命令:

$ php -f test.php foo bar baz
int(4)
array(4) {
  [0]=>
  string(8) "test.php"
  [1]=>
  string(3) "foo"
  [2]=>
  string(3) "bar"
  [3]=>
  string(3) "baz"
}

另外,请查看using PHP from the command line

答案 1 :(得分:7)

除了argv(如Ionut所述),您可以使用环境变量:

E.g:

var = 3 php -f test.php

在test.php中:

$var = getenv("var");

答案 2 :(得分:6)

如果你想保持命名参数几乎像var = 3&amp; foo = bar(而不是$argv提供的位置参数)getopt()可以帮助你。

答案 3 :(得分:4)

除了使用argc所指示的argvIonut G. Stan之外,您还可以使用可以解析unix样式命令行选项的PEAR模块Console_Getopt。有关详细信息,请参阅this article

或者,Zend_Console_Getopt类的Zend Framework中有类似的功能。

答案 4 :(得分:3)

许多解决方案根据订单的顺序将参数放入变量中。例如,

myfile.php 5 7

将5放入第一个变量,7放入下一个变量。

我想要命名参数:

myfile.php  a=1 x=8

这样我就可以在PHP代码中将它们用作变量名。

IonuţG。Stan给出的链接 http://www.php.net/manual/en/features.commandline.php

给了我答案。

sep16 at psu dot edu:

您可以使用parse_str()函数轻松地将命令行参数解析为$ _GET变量。

<?php
parse_str(implode('&', array_slice($argv, 1)), $_GET);
?>

它的行为与cgi-php完全一样。

$ php -f somefile.php a=1 b[]=2 b[]=3

这会将$ _GET ['a']设置为'1',将$ _GET ['b']设置为数组('2','3')。

相关问题