The server (should) know how to resolve the hostname to the correct IP address, even if it is not connected to the Internet.
So, all you have to do is get the host name and then resolve the host name to an IP address. Something like this should work fine for you:
$ip = gethostbyname(gethostname());
Regardless of whether the hostname is registered in DNS, the file / etc / hosts or even ActiveDirectory, as long as it is resolvable in some way, this will provide you with a resolved IP address.
You may also have to plan other options. Therefore, check what worked above, if it is not, then you need to return to other parameters:
$_SERVER['HTTP_HOST'] contains the address that was entered in the address bar of the browser to access the page. If you page by typing (for example) http://192.168.0.1/index.php into the browser $_SERVER['HTTP_HOST'] will be 192.168.0.1 .- If you used the DNS name to access the page,
gethostbyname($_SERVER['HTTP_HOST']) ; will turn this DNS name into an IP address. $_SERVER['SERVER_NAME'] contains the name configured in the web server configuration as the server name. If you are going to use this, you could just simply copy it into PHP.$_SERVER['SERVER_ADDR'] will contain the operating system the primary IP address of the server. This may or may not be the IP address that was used to access the page, and it may or may not be the IP address of the web server attached to it. This is highly dependent on the OS and server configuration. if the server has one IP address, this is probably a safe bet, although there are situations where it may contain 127.0.0.1 .
You can try something like:
<?php $ip = gethostbyname(gethostname()); // if we didn't get an IP address if ($ip === gethostname()){ // lets see if we can get it from the // configured web server name $ip = gethostbyname($_SERVER['SERVER_NAME']); // if we still don't have an IP address if ($ip === $_SERVER['SERVER_NAME']){ // Then we default to whatever the OS // is telling us is it primary IP address $ip = $_SERVER['SERVER_ADDR']; } }
If you want to use the command line (a dangerous, potential attack vector) on linux, you can do something like:
//then all non 127.0.0.1 ips should be in the $IPS variable echo exec('/sbin/ifconfig | grep "inet addr:" | grep -v "127.0.0.1" | cut -d: -f2 | awk \'{ print $1}\'', $IPS); $ip = ''; $foundIps = count($IPS); switch($foundIps){ case 0: print "Crud, we don't have any IP addresses here!\n"; $ip = '127.0.0.1'; break; case 1: print "Perfect, we found a single usable IP address, this must be what we want!\n"; $ip = $IPS[0]; break; default: print "Oh snap, this machine has multiple IP addresses assigned, what you wanna do about that?\n" // I'm crazy, I'll just take the second one! $ip = $IPS[1]; }
bubba source share