2012-02-14 93 views
3

我想写下一个脚本来获取一些在线数据;脚本应该由cron作业或php cli以及标准GET HTTP请求调用。正如PHP网站$_SERVER['argv']所述,应该适合我的需求:

传递给脚本的参数数组。当脚本在 命令行上运行时,可以通过C风格访问命令行参数 。当通过GET方法调用时,这将包含 查询字符串。

但是我不能让它与标准的HTTP GET请求一起工作。 $_SERVER['argv']没有设置。我错过了什么?

<?php 
    // jobs/fetch.php 
    var_dump($_SERVER['argv']); 
?> 

CLI输出php jobs/fetch.php -a -bhello

array(3) { 
    [0]=> 
    string(14) "jobs/fetch.php" 
    [1]=> 
    string(2) "-a" 
    [2]=> 
    string(7) "-bhello" 
} 

GET输出jobs/fetch.php?a=&b=hello

注意:未定义指数:ARGV在工作/ fetch.php。

回答

14

如果你想$_SERVER['argc']$_SERVER['argv']$argc,要当你不在CLI模式下运行注册该手册并没有说明这一点非常好,但是,随后php.iniregister_argc_argv需要在php.ini中启用(默认情况下为关闭性能原因)。

你可以做以下获得argv,或查询字符串ARGS取决于如何运行脚本:

if (php_sapi_name() == 'cli') { 
    $args = $_SERVER['argv']; 
} else { 
    parse_str($_SERVER['QUERY_STRING'], $args); 
} 

这里有一些细节,从php.ini

; This directive determines whether PHP registers $argv & $argc each time it 
; runs. $argv contains an array of all the arguments passed to PHP when a script 
; is invoked. $argc contains an integer representing the number of arguments 
; that were passed when the script was invoked. These arrays are extremely 
; useful when running scripts from the command line. When this directive is 
; enabled, registering these variables consumes CPU cycles and memory each time 
; a script is executed. For performance reasons, this feature should be disabled 
; on production servers. 
; Note: This directive is hardcoded to On for the CLI SAPI 
; Default Value: On 
; Development Value: Off 
; Production Value: Off 
; http://php.net/register-argc-argv 

参见http://www.php.net/manual/en/reserved.variables.argv.phpparse_str()

3

你将不得不使用$_GET$_SERVER['argv']取决于你的脚本是如何被调用。两者都不使用。

例如:

if(!empty($_SERVER['argv'][0]) { 
    $a = $_SERVER['argv'][1]; 
    $b = $_SERVER['argv'][2]; 
} else { 
    $a = $_GET['a']; 
    $b = $_GET['b']; 
}