views:

1744

answers:

7

I can't find 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.

Does anyone have suggestions?

Thanks, Justin Noel AppBeacon.com

+1  A: 

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

anon
No server in the sense that no WEB server is involved. However, I want the name of the server the script itself is actually running on.
Justin
A: 

Write your server name in your config file or something similar.

glavić
No thanks. I want code that can be moved from one server to another without needing config file changes.
Justin
+1  A: 

Try:

$servername = `hostname`;
jonstjohn
+1  A: 

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.

mikl
+11  A: 
echo php_uname("n");

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

Uwe Mesecke
A: 

@Uwe Mesecke : I can't vote up or down. Your answer is the best. Although, it is not 100% portable, because some hosts respond with extra garbage in that. Mac OS X Leopard and OpenSolaris all respond with just the hostname. RHEL3 (shudder) responds with all kinds of junk.

Justin
You can mark the answer as accepted by clicking on the symbol under the votes of the answer.
Wookai
A: 

Two solutions: 1) Create a txt-file containing the hostname of the server and then let the script read it. 2) Call the CLI with hostname as parameter

trond

trond