PHP Server Name from Command Line

2019-01-22 17:31发布

Is there a way to detect the name of the server running a PHP script from the command line?

There are numerous ways to do this for PHP accessed via HTTP. But there does not appear to be a way to do this for CLI.

For example:

$_SERVER['SERVER_NAME'] 

is not available from the command line.

9条回答
叛逆
2楼-- · 2019-01-22 18:01

Possibly because if you run a script from the command line, no server is involved?

查看更多
SAY GOODBYE
3楼-- · 2019-01-22 18:13
<?php
echo gethostname(); // may output e.g,: sandie

See http://php.net/manual/en/function.gethostname.php

gethostname() is a convenience function which does the same as php_uname('n') and was added as of PHP 5.3

查看更多
老娘就宠你
4楼-- · 2019-01-22 18:15

One of these may have the server name:

print_r($_SERVER)
var_dump($_SERVER) 
echo $_SERVER['HOSTNAME']

Gives me the name of the server.

查看更多
时光不老,我们不散
5楼-- · 2019-01-22 18:18

In order to get the hostname from the commandline you would need to also run using php -r. On linux I used:

~#php -r 'echo php_uname("n");'
hostname

On windows I used:

D:\xampp\php>php -r "echo php_uname('n');"
MB-PC

Additionally, when accessed via the console PHP does not provide many of the classic $_SERVER values but on the server I accessed only has the following keys:

root@hermes:~# php -r 'foreach($_SERVER as $key =>$value){echo $key.",";}'
TERM,SHELL,SSH_CLIENT,SSH_TTY,USER,LS_COLORS,MAIL,PATH,PWD,LANG,SHLVL,HOME,LOGNAME,SSH_CONNECTION,LESSOPEN,LESSCLOSE,_,PHP_SELF,SCRIPT_NAME,SCRIPT_FIL
ENAME,PATH_TRANSLATED,DOCUMENT_ROOT,REQUEST_TIME,argv,argc
查看更多
迷人小祖宗
6楼-- · 2019-01-22 18:20
Rolldiameter
7楼-- · 2019-01-22 18:21

Call the CLI and use the gethostname command:

php -r "echo gethostname();"

Prints:

your_hostname
查看更多
登录 后发表回答