我正试图写一个脚本来获取一些在线数据;脚本应该由cron作业或php-cli调用,并使用标准的GET HTTP请求。正如PHP网站上所说,$_SERVER['argv']
应该符合我的需求:
传递给脚本的参数数组。当脚本在命令行,这使C样式可以访问命令行参数。当通过GET方法调用时,它将包含查询字符串。
然而,我无法让它与标准的HTTPGET请求一起工作。未设置$_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
:
注意:未定义的索引:jobs/fetch.php.中的argv
手册没有很好地说明这一点,但是,如果您希望在不以CLI
模式运行时注册$_SERVER['argc']
、$_SERVER['argv']
、$argc
、$argv
,则需要在php.ini中启用php.ini
值register_arg_argv(默认情况下[出于性能原因]关闭)。
您可以执行以下操作来获取argv
,或者根据脚本的运行方式查询字符串参数:
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.php和parse_str()。
根据脚本的调用方式,您必须使用$_GET
或$_SERVER['argv']
。两者都不使用。
例如:
if(!empty($_SERVER['argv'][0]) {
$a = $_SERVER['argv'][1];
$b = $_SERVER['argv'][2];
} else {
$a = $_GET['a'];
$b = $_GET['b'];
}