PHP passing $_GET in the Linux command prompt PHP passing $_GET in the Linux command prompt linux linux

PHP passing $_GET in the Linux command prompt


From this answer on Server Fault:

Use the php-cgi binary instead of just php, and pass the arguments on the command line, like this:

php-cgi -f index.php left=1058 right=1067 class=A language=English

Which puts this in $_GET:

Array(    [left] => 1058    [right] => 1067    [class] => A    [language] => English)

You can also set environment variables that would be set by the web server, like this:

REQUEST_URI='/index.php' SCRIPT_NAME='/index.php' php-cgi -f index.php left=1058 right=1067 class=A language=English


Typically, for passing arguments to a command line script, you will use either the argv global variable or getopt:

// Bash command://   php -e myscript.php helloecho $argv[1]; // Prints "hello"// Bash command://   php -e myscript.php -f=world$opts = getopt('f:');echo $opts['f']; // Prints "world"

$_GET refers to the HTTP GET method parameters, which are unavailable on the command line, since they require a web server to populate.

If you really want to populate $_GET anyway, you can do this:

// Bash command://   export QUERY_STRING="var=value&arg=value" ; php -e myscript.phpparse_str($_SERVER['QUERY_STRING'], $_GET);print_r($_GET);/* Outputs:     Array(        [var] => value        [arg] => value     )*/

You can also execute a given script, populate $_GET from the command line, without having to modify said script:

export QUERY_STRING="var=value&arg=value" ; \php -e -r 'parse_str($_SERVER["QUERY_STRING"], $_GET); include "index.php";'

Note that you can do the same with $_POST and $_COOKIE as well.


Sometimes you don't have the option of editing the PHP file to set $_GET to the parameters passed in, and sometimes you can't or don't want to install php-cgi.

I found this to be the best solution for that case:

php -r '$_GET["key"]="value"; require_once("script.php");'

This avoids altering your PHP file and lets you use the plain php command. If you have php-cgi installed, by all means use that, but this is the next best thing. I thought this options was worthy of mention.

The -r means run the PHP code in the string following. You set the $_GET value manually there, and then reference the file you want to run.

It's worth noting you should run this in the right folder, often, but not always, the folder the PHP file is in. 'Requires' statements will use the location of your command to resolve relative URLs, not the location of the file.