PHP how to get local IP of system

From CLI

PHP < 5.3.0

$localIP = getHostByName(php_uname('n'));

PHP >= 5.3.0

$localIP = getHostByName(getHostName());


$_SERVER['SERVER_ADDR']

This is an old post, but get it with this:

function getLocalIp()
{ return gethostbyname(trim(`hostname`)); }

For example:

die( getLocalIp() );

Found it on another site, do not remove the trim command because otherwise you will get the computers name.

BACKTICKS (The special quotes): It works because PHP will attempt to run whatever it's between those "special quotes" (backticks) as a shell command and returns the resulting output.

gethostbyname(trim(`hostname`));

Is very similar (but much more efficient) than doing:

$exec = exec("hostname"); //the "hostname" is a valid command in both windows and linux
$hostname = trim($exec); //remove any spaces before and after
$ip = gethostbyname($hostname); //resolves the hostname using local hosts resolver or DNS