I have a site that provides polls for web masters. One of my clients wants the following feature: shows results including the city, country where voters are located, or at least the state in the U.S.

The only way to do this is by IP address (I think). But how do I link a city/country to an IP address? Any help is really appreciated. Any PHP code out there that can do this?

You will need some sort of API or query a URL that will return the IPs City,state, etc. For a URL try this.
geoPlugin’s free and easy PHP geolocation webservice explained
IP location XML API :: IPInfoDB
On their sites they provide some code examples.
Basically you send their server an IP address and they return the info.
Watch out for security and user privacy.

Should also inform the client that it may not be 100% accurate, if they’re wanting to get down to city level - IE: I live in a suburb of Atlanta, but if you GeoIP my external IP address, you get Athens instead.

It should get you the right state/region-within-state, but anything lower than that is a bit of a guessing game with most IP’s.

Yes, State is most of the time accurate, county, depends, City is hit or miss. Also it can’t (obviously) account for an IP proxy.

You could also check out the GeoLocation API newer browsers are supportingm with geo.js or Gears as a backup for IE and whoever else doesn’t support.

However this does ask users if you may get their coords, and if you want silent monitoring you’ll miss those who either don’t run JS on older browsers and those who opt out completely. You would though be able to get away with the faster, less accurate settings if you just want state and city.

Yep, accuracy is certainly not guaranteed. Always keep that in mind.

For instance, the last time I checked, my IP gave the location of Richmond, VA even though I’m actually nearly 600 miles away. :shifty:

When you need to check for massive GetLocations, then it is better to go for script to work on your local server, this avoid huge number of calls to third party webservice and block your IP.

Here is some free resources available and i used it for my clients

GeoLiteCity from MaxMind
FREE IP to Country Database (IPV4 and IPV6)

As Force Flow told, sometimes you will not get exact city.
And one more thing, you need to update their database monthly once, to keep database updated.