Reputation: 1190
I have a php application that is installed on several servers and all of our developers laptops. I need a fast and reliable way to get the server's hostname or some other unique and reliable system identifier. Here's what we have thought of so far:
<? $hostname = (!empty($_ENV["HOSTNAME"])) ? $_ENV["HOSTNAME"] : env('HOSTNAME'); ?>
<? $hostname = gethostbyaddr($_SERVER['SERVER_ADDR']); ?>
<? $hostname = exec('hostname'); ?>
What do you think?
Upvotes: 59
Views: 126935
Reputation: 17354
The accepted answer of gethostname()
may, in fact, give you an inaccurate value as it does in my case:
gethostname() = my-macbook-pro (which is my machine name)
$_SERVER['host_name'] = mysite.git (which is my website name)
The value from gethostname()
is obviously wrong. Be careful with it.
Upvotes: 2
Reputation: 1599
Whether your webserver is Apache, NGINX or otherwise; you can set the headers which are forwarded to your PHP application. While slightly safer on its own, due to browser behavior, the Origin header is useful for this scenario.
For example, with NGINX:
Add an explicit set to fastcgi_param HTTP_ORIGIN
either as a hard-coded string, based on $server_name or $ssl_server_name. This is done in an NGINX server block context which will ensure host strings matched with the header, but you don't pass the header directly to your app. Apache configs have the same information available in the virtual host configs.
This way, the string going to your app is predefined by your project. The main point is that user submitted headers will be checked against accepted values -- but never passed along. The existing accepted value will be passed along instead.
Upvotes: 0
Reputation: 16924
I am running PHP version 5.4 on shared hosting and both of these both successfully return the same results:
php_uname('n');
gethostname();
Upvotes: 2
Reputation: 11711
$hostname = gethostname();
For PHP < 5.3.0 but >= 4.2.0 use this:
$hostname = php_uname('n');
For PHP < 4.2.0 use this:
$hostname = getenv('HOSTNAME');
if(!$hostname) $hostname = trim(`hostname`);
if(!$hostname) $hostname = exec('echo $HOSTNAME');
if(!$hostname) $hostname = preg_replace('#^\w+\s+(\w+).*$#', '$1', exec('uname -a'));
Upvotes: 44
Reputation: 27313
php_uname but I am not sure what hostname you want the hostname of the client or server.
plus you should use cookie based approach
Upvotes: 1
Reputation: 94167
What about gethostname()?
Edit: This might not be an option I suppose, depending on your environment. It's new in PHP 5.3. php_uname('n') might work as an alternative.
Upvotes: 46