PHP has an extension for that.
From PHP.net:
The GeoIP extension allows you to find the location of an IP address.
City, State, Country, Longitude, Latitude, and other information as
all, such as ISP and connection type can be obtained with the help of
GeoIP.
For example:
$record = geoip_record_by_name($ip);
echo $record['city'];