gre*_*emo 5 php get command-line-interface query-string
我正在尝试写下一个脚本来获取一些在线数据; 脚本应该由cron作业或php cli以及标准的GET HTTP请求调用.如PHP网站所述,$_SERVER['argv']应符合我的需求:
传递给脚本的参数数组.在命令行上运行脚本时,这将提供对命令行参数的C样式访问.通过GET方法调用时,它将包含查询字符串.
但是我无法使用标准的HTTP GET请求.$_SERVER['argv']没有设置.我错过了什么?
<?php
// jobs/fetch.php
var_dump($_SERVER['argv']);
?>
Run Code Online (Sandbox Code Playgroud)
CLI输出 php jobs/fetch.php -a -bhello:
array(3) {
[0]=>
string(14) "jobs/fetch.php"
[1]=>
string(2) "-a"
[2]=>
string(7) "-bhello"
}
Run Code Online (Sandbox Code Playgroud)
GET输出 jobs/fetch.php?a=&b=hello:
注意:未定义的索引:jobs/fetch.php中的argv.
dre*_*010 16
该手册并没有说明这一点非常好,但是,如果你想$_SERVER['argc'],$_SERVER['argv'],$argc,$argv要当你不是在运行注册CLI模式,则php.ini值register_argc_argv需要在php.ini中启用(默认关闭[出于性能的考虑] ).
您可以执行以下操作来获取argv或查询字符串参数,具体取决于脚本的运行方式:
if (php_sapi_name() == 'cli') {
$args = $_SERVER['argv'];
} else {
parse_str($_SERVER['QUERY_STRING'], $args);
}
Run Code Online (Sandbox Code Playgroud)
以下是一些细节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
Run Code Online (Sandbox Code Playgroud)
另见http://www.php.net/manual/en/reserved.variables.argv.php和parse_str().
小智 5
您将不得不使用$_GET 或 $_SERVER['argv']取决于您的脚本的调用方式。两者都不使用任何一种。
例如:
if(!empty($_SERVER['argv'][0]) {
$a = $_SERVER['argv'][1];
$b = $_SERVER['argv'][2];
} else {
$a = $_GET['a'];
$b = $_GET['b'];
}
Run Code Online (Sandbox Code Playgroud)