PHP passing $_GET in linux command prompt

2019-01-02 22:10发布

Say we usually access via

http://localhost/index.php?a=1&b=2&c=3

How do we execute the same in linux command prompt?

php -e index.php

But what about passing the $_GET variables? Maybe something like php -e index.php --a 1 --b 2 --c 3? Doubt that'll work.

Thank you!

标签: php linux
13条回答
成全新的幸福
2楼-- · 2019-01-02 22:54

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

// bash command:
//   php -e myscript.php hello
echo $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 in 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.php
parse_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.

查看更多
登录 后发表回答