简体   繁体   中英

PHP - Server name from the command line

Apparently $_SERVER['SERVER_NAME'] is set only when executing the php script from the browser.

Is there any way to know the server's name from the command line ?

I tried php_uname("n") as proposed in this discussion PHP Server Name from Command Line . But it doesn't work for me, it returns my username instead of the server's name.

There is no "server" involved when executing a script from the command line. You're just running a program on a machine . That machine isn't per se associated with any domain name. One machine can run multiple web servers which are each responsible for several domains. So $_SERVER['SERVER_NAME'] , which comes from the web server's configuration (eg Apache's ServerName directive), only makes sense in the context of an incoming HTTP request.

You'll need to manually configure/tell your script what domain it should work on, it can't detect it without context.

well, you need to know that there are some different between SAPI's in PHP, when you are running a PHP script in your web browser, you are using the HTTP Server SAPI ( Apache2 or nginx or whatever ), so the returned data in the $_SERVER variable will depends on the headers that the web server itself will throw to PHP, While in the terminal you are running PHP Under CLI SAPI which is serverless so to speak Unless you are using the built-in php server .

Take a look at the $_SERVER manual page :-

$_SERVER is an array containing information such as headers, paths, and script locations. The entries in this array are created by the web server. There is no guarantee that every web server will provide any of these; servers may omit some, or provide others not listed here. That said, a large number of these variables are accounted for in the » CGI/1.1 specification, so you should be able to expect those.

which is mean - again - that the data that will $_SERVER variable will hold will depends on the information that the web server will return/throw .


As a workaround you can check if the script is running under the CLI SAPI, and then set some custom values for the $_SERVER variable

Use print_r($_SERVER) to see all the attributes on server variables. Maybe another one will fit your needs.

Cheers!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM