I'm trying to write a script to fetch data. The script should be invoked either by
As stated on PHP website, $_SERVER['argv'] should fit my needs:
Array of arguments passed to the script. When the script is run on the command line, this gives C-style access to the command line parameters. When called via the GET method, this will contain the query string.
However, I can't get it to work with standard HTTP GET request. $_SERVER['argv'] is not set.
What am I missing?
This is my jobs/fetch.php:
<?php
var_dump($_SERVER['argv']);
CLI output as expected:
$ php jobs/fetch.php -a -bhello
array(3) {
[0]=>
string(14) "jobs/fetch.php"
[1]=>
string(2) "-a"
[2]=>
string(7) "-bhello"
}
GET Request response requesting jobs/fetch.php?a=&b=hello fails:
Notice: Undefined index: argv in jobs/fetch.php.
Update: As of PHP 8.5, this setting is deprecated and from PHP 9 onward it is no longer be possible to register the argc and argv variables when PHP is running under a web server.
See the Deprecate the register_argc_argv INI directive RFC for more information.
The manual didn't state this very well, but, if you want $_SERVER['argc'], $_SERVER['argv'], $argc, $argv to be registered when you are not running in CLI mode, then the php.ini value register_argc_argv needs to be enabled in php.ini (off by default for performance reasons).
You could do the following to get argv, or query string args depending on how the script is running:
if (php_sapi_name() == 'cli') {
$args = $_SERVER['argv'];
} else {
parse_str($_SERVER['QUERY_STRING'], $args);
}
Here are some details from 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
See also $argv and parse_str().