2012-02-14 70 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']; 
}