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条回答
forever°为你锁心
2楼-- · 2019-01-22 18:23

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.

查看更多
干净又极端
3楼-- · 2019-01-22 18:23

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.
?> 
查看更多
Juvenile、少年°
4楼-- · 2019-01-22 18:24

Try:

$servername = trim(`hostname`);
查看更多
登录 后发表回答