PHP Server Name from Command Line

点点圈 提交于 2019-12-17 23:15:17

问题


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.


回答1:


echo php_uname("n");

see http://php.net/manual/en/function.php-uname.php




回答2:


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




回答3:


The SERVER_NAME is not available when you run PHP from the CLI for that very same reason.

When you run PHP from the CLI, you start your own PHP intepreter that runs whatever code you passed to it, without any kind of server. So from the CLI, PHP knows nothing about your web server that you do not explicitly tell it.




回答4:


Try:

$servername = trim(`hostname`);



回答5:


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:


You can add your php script to command line that will set $_SERVER['SERVER_NAME'] for you. Here is how I'm using it:

C:\SDK\php-5.5.25-Win32-VC11-x86\php.exe -S localhost:8080 -t D:\Projects\Sites\mysite router.php

router.php

<?php
$_SERVER['SERVER_NAME'] = 'localhost:8080';
return false;    // serve the requested resource as-is.
?> 



回答7:


Call the CLI and use the gethostname command:

php -r "echo gethostname();"

Prints:

your_hostname



回答8:


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




回答9:


One of these may have the server name:

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

Gives me the name of the server.



来源:https://stackoverflow.com/questions/626416/php-server-name-from-command-line

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