A “slightly better” get_ip() function for PHP

When I’ve got a nasty case of insomnia, such as the current time, I like to browse the web and work on small projects – nothing to get me too engrossed, but still, enough to be useful, and have something functional by when I finally slumber.

As previously mentioned, I usually give David Grant’s QuickBlog a view to see what he’s been up to.

I was a bit suprised to see his rehashing of a rather frightful get_ip() function which was trivially re-encoded for PHP4’s superglobals, yet still had fallback code for PHP3.

The biggest problem is, you can’t trust the data given to you from anyone. Especally when it’s a variable in PHP! Thankfully, the $_SERVER superglobals make it a bit more functional, but I still don’t trust them. I’ve rewritten his get_ip function:

= 167772160) && ($lrealip <= 184549375)) || (($lrealip >= -1408237568) && ($lrealip <= -1407188993)) || (($lrealip >= -1062731776) && ($lrealip <= -1062666241)) || ($lrealip == 2130706433)) { $realip = “local”; } return $realip; } } } }

?>

As you can see, the function is a bit quirky that it returns alphanumeric text; I’ve written this to be a ‘poor man’s catch-all’. It will return the data of “local” for a local subnet, “unknown” if it isn’t sure, or the IP of the host.

“But Shawn,” you may inquire, “how do I know if it’s an IP or not?”

Ah, good question! I’ve even got it within the code itself! Here’s a sample snippit that decides if the data is a dotted quad, or plaintext. I’ve tried to break everything down and keep it simple. This demonstration merely attempts to find an IP address and log it to a MySQL database logging a “visitor”. About ten more lines of code and a