[ACCEPTED]-PHP Server Name from Command Line-command-line-interface

Accepted answer
Score: 91
Score: 21
<?php
echo gethostname(); // may output e.g,: sandie

See http://php.net/manual/en/function.gethostname.php

gethostname() is a convenience function 2 which does the same as php_uname('n') and was added as 1 of PHP 5.3

Score: 12

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

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

Score: 3

Try:

$servername = trim(`hostname`);

0

Score: 3

Call the CLI and use the gethostname command:

php -r "echo gethostname();"

Prints:

your_hostname

0

Score: 3

In order to get the hostname from the commandline you 6 would need to also run using php -r. On 5 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 4 accessed via the console PHP does not provide 3 many of the classic $_SERVER values but 2 on the server I accessed only has the following 1 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
Score: 3

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

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

router.php

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

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

More Related questions