Accessing $_SERVER variables from command line

雨燕双飞 提交于 2019-12-02 10:39:55

问题


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?


回答1:


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




回答2:


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
}


来源:https://stackoverflow.com/questions/24287716/accessing-server-variables-from-command-line

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!