views:

47

answers:

2

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 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?

+6  A: 

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".

Rich Adams
Thanks! Also, if I use single quotes in the argument, no need for escaping :)
A: 

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.

Nicolò Martini