tim peterson
tim peterson

Reputation: 24315

Accessing $_SERVER variables from command line

How do I access $_SERVER variables I've set from the command line in PHP?

When I try to call a PHP method I've created I get the following error, which shows that all the $_SERVER variables are only defined when one calls my app via its URLs, i.e., webserver:

ERROR - Undefined index: MY_VAR /www/html/some_file.php
ERROR - Undefined index: MY_OTHER_VAR /www/html/some_file.php

To be more specific I'm using Codeigniter, but don't believe that is the issue.

Thoughts?

Upvotes: 3

Views: 12281

Answers (2)

Shotgun
Shotgun

Reputation: 678

Some $_SERVER variables aren't accessible from command line, which is logical, when using command line, you don't specify a method (GET/POST etc.), so what would you expect $_SERVER["HTTP_METHOD"] to be?

One solution to fetch through all the variables set in $_SERVER is to dump it :

var_dump($_SERVER);

And then call your file from command line to see what variables are set.

Other than that, always be careful when using $_SERVER variable, its behaviour really depends on the platform, and other factors.

always try :

if(isset($_SERVER["MY_VAR"])) {
  // do what you want here
}

Upvotes: 0

Joel
Joel

Reputation: 3060

If you're setting the server variables in your web server config, then they won't be present when you access PHP via the command line. (Since the web server won't be involved at all.)

To use $_SERVER variables in your CLI PHP script, see: Set $_SERVER variable when calling PHP from command line?


To summarize:

run: VALUE_ONE=1 ANOTHER_VALUE=2 php cli.php

Upvotes: 9

Related Questions