Hardware Reference
In-Depth Information
Project 28
IP Geocoding
The next example uses the client's IP address to get its latitude and longitude. It gets
this information from www.hostip.info , a community-based IP geocoding project. The
data there is not always the most accurate, but it is free. This script also uses the HTTP
user agent to determine whether the client is a desktop browser or an Ethernet module.
It then formats its response appropriately for each device.
Locate It
Save this to
your server as
<?php
/* IP geocoder
Context: PHP
Uses a client's IP address to get latitude and longitude.
Uses the client's user agent to format the response.
*/
// initialize variables:
$lat = 0;
$long = 0;
$country = "unknown";
ip_geocoder.php.
// check to see what type of client this is:
$userAgent = getenv('HTTP_USER_AGENT');
// get the client's IP address:
$ipAddress = getenv('REMOTE_ADDR');
8
The website www.hostip.info will
return the latitude and longitude from
the IP address in a convenient XML
format. The latitude and longitude are
inside a tag called <gml:coordinates> .
That's what you're looking for. First,
format the HTTP request string and
make the request. Then wait for the
results in a while loop, and separate the
results into the constituent parts.
// use http://www.hostIP.info to get the latitude and longitude
// from the IP address. First, format the HTTP request string:
$IpLocatorUrl = "http://api.hostip.info/?&position=true&ip=";
// add the IP address:
$IpLocatorUrl .= $ipAddress;
// make the HTTP request:
$filePath = fopen ($IpLocatorUrl, "r");
// as long as you haven't reached the end of the incoming text:
while (!feof($filePath)) {
// read one line at a time
$line = fgets($filePath, 4096);
// if the line contains the coordinates, then you want it:
if (preg_match('/<gml:coordinates>/', $line)) {
$position = strip_tags($line); // strip the XML tags
$position = trim($position); // trim the whitespace
$coordinates = explode(",",$position); // split on the comma
$lat = $coordinates[0];
$long = $coordinates[1];
}
}
ยป
Search WWH ::




Custom Search