Get the local IP within PHP on a Raspberry Pi (Raspbian)


I’m currently working on interfacing a Raspberry Pi with an Arduino. The Pi needs to tell the Arduino it’s IP address on the LAN in order for it to be displayed on an LCD screen.
My code running on the Pi is PHP. It’s usually pretty straightforward to get your local IP address from within PHP.
I just make use of the handy $_SERVER array like so:

$ip = $_SERVER['SERVER_ADDR'];

failed. SERVER_ADDR wasn’t set. Using my initiative, I threw together the following function, which works a treat:

function getIp()
{
	exec('/sbin/ifconfig', $resultArray);
	$result = implode(",", $resultArray);
 
	$ip = preg_match('/eth0.*?inet\saddr:([\d]{1,3}\.[\d]{1,3}\.[\d]{1,3}\.[\d]{1,3})\s/', $result, $matches);
 
	return isset($matches[1])?$matches[1]:false;
}

It basically calls the linux command ‘ifconfig’. The IP address is then extracted from the results.
This should work for any occasion where $_SERVER[‘SERVER_ADDR’] isn’t available, as a fallback.
Feel free to use this in your own projects!

Like it? Share it!

Copyright © 2018. Created by Hayden Kibble.