The typical way to get your user's IP address via PHP is with $_SERVER['REMOTE_ADDR']
. This is pretty solid, but can lead to some IP detections that are surprisingly far away from the user's actual location.
Craft also has it's own IP detection with craft()->request->userHostAddress
. This jumps through a few more hoops before finally falling back to $_SERVER['REMOTE_ADDR']
.
Which is better in terms of geolocation accuracy?
The Craft docs say this:
Considering any of these server vars besides REMOTE_ADDR can be spoofed, this method should not be used when you need a trusted source for the IP address. Use
$_SERVER['REMOTE_ADDR']
instead.
I don't think my source needs to be that "trusted". I'm using the IP address for best-guess geolocation, not for any sort of security purposes.
I'm just looking for whichever one will pinpoint closest to the human user.
Disclaimer: I'm well aware that IP detection is a lousy way to pinpoint users, and that HTML5 / JS offers much more accurate geolocation results. But when using that method, geolocation is optional to the user, and they may deny permission to share their location. It's good to have the IP detection as a fallback.