开发者

$_SERVER not set with command line -r option?

When I try to print the $_SERVER variable from a command line php, it thinks $_SERVER is not set.

$ php -r "print_r($_SERVER);"
Warning: print_r() expects at least 1 parameter, 0 given in Command line code on line 1

However, when it's in a file, running it 开发者_JAVA百科from the command line has it set

$ cat test.php
<?
print_r($_SERVER);

$ php test.php
Array
(
    [TERM] => xterm
    [SHELL] => /bin/bash
    [SSH_CLIENT] => 192.168.1.101 49319 22
    [SSH_TTY] => /dev/pts/0
...

Why?


You need to escape the $ character on the command line.

php -r "print_r(\$_SERVER);"

Otherwise the shell will think it's a shell variable called _SERVER (which you don't have set to anything) and so what's actually been run is php -r "print_r();", which is why you get the error "print_r() expects at least 1 parameter, 0 given".


From the official documentation

You may or may not find any of the following elements in $_SERVER. Note that few, if any, of these will be available (or indeed have any meaning) if running PHP on the command line.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜