Justin Noel
Justin Noel

Reputation: 6205

PHP Server Name from Command Line

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.

Upvotes: 42

Views: 37412

Answers (9)

Vladyslav Litunovsky
Vladyslav Litunovsky

Reputation: 546

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

Upvotes: 3

Alexander V. Ilyin
Alexander V. Ilyin

Reputation: 2460

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

Upvotes: 21

trond
trond

Reputation: 31

Call the CLI and use the gethostname command:

php -r "echo gethostname();"

Prints:

your_hostname

Upvotes: 3

ebonit
ebonit

Reputation: 13

One of these may have the server name:

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

Gives me the name of the server.

Upvotes: -6

Menelaos
Menelaos

Reputation: 25727

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

Upvotes: 3

jonstjohn
jonstjohn

Reputation: 60266

Try:

$servername = trim(`hostname`);

Upvotes: 3

Uwe Mesecke
Uwe Mesecke

Reputation: 1961

echo php_uname("n");

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

Upvotes: 94

mikl
mikl

Reputation: 24267

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.

Upvotes: 13

anon
anon

Reputation:

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

Upvotes: 2

Related Questions