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

Accepted answer
Score: 91
Score: 21
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


$servername = trim(`hostname`);


Score: 3

Call the CLI and use the gethostname command:

php -r "echo gethostname();"




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");'

On windows I used:

D:\xampp\php>php -r "echo php_uname('n');"

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.",";}'
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


$_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