Is there a PHP function or variable giving the local host name?

六眼飞鱼酱① 提交于 2020-01-01 11:04:26

问题


When a script runs under Apache, I insert $_SERVER['SERVER_NAME'] value into an error reporting e-mail message.

However, if a Web script forks a "worker" job with nohup php ..., $_SERVER['SERVER_NAME'] appears to be empty there. Thus, if an error occurs, it's reported without a host name.

Can I reliably get the host name by means of PHP, without calling Unix hostname command?


回答1:


php_uname("n")

(PHP 4 >= 4.0.2, PHP 5)
php_uname — Returns information about the operating system PHP is running on

php_uname() returns a description of the operating system PHP is running on. This is the same string you see at the very top of the phpinfo() output. For the name of just the operating system, consider using the PHP_OS constant, but keep in mind this constant will contain the operating system PHP was built on.

On some older UNIX platforms, it may not be able to determine the current OS information in which case it will revert to displaying the OS PHP was built on. This will only happen if your uname() library call either doesn't exist or doesn't work.




回答2:


For PHP >= 5.3.0 use this:

$hostname = gethostname();

For PHP < 5.3.0 but >= 4.2.0 use this:

$hostname = php_uname('n');

For PHP < 4.2.0 you can try one of these:

$hostname = getenv('HOSTNAME'); 
$hostname = trim(`hostname`); 
$hostname = preg_replace('#^\w+\s+(\w+).*$#', '$1', exec('uname -a')); 



回答3:


You can use _GLOBALS['MACHINENAME'] to obtain the information straight from the globals array.



来源:https://stackoverflow.com/questions/211885/is-there-a-php-function-or-variable-giving-the-local-host-name

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