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.


Between the two, I'd say that craft()->request->userHostAddress is going to be a more reliable method. It tries to take into account things like clients going though proxy servers, shared ISP IP addresses, etc. whereas you don't know any of that just relying on $_SERVER['REMOTE_ADDR'].

But, as you pointed out, none of this is guaranteed to be reliable.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.