Rasher's Toolbox

Back

ipinfo

mixed im_status(string host) -- Attempt to geolocate a host, using the hostip.info service

Description

This function will attempt to find the geographical location of a host. If successful, the function will return an array with the following elements:

ip - IP of the host
host - Hostname of the host (may be identical to ip)
cc - 2-letter country code
country - Country of host
city - City of host
latitude - Coordinates of host (latitude)
longitude - Coordinates of host (longitude)

City, longitude and latitude may not be present. false is returned if the host cannot be looked up.

Example

<?php
  $location 
ipinfo('rasher.dk');
  echo 
$location['country'];
?>

This will output:

Danmark

Source

Published under the terms of the BSD License

<?php
function ipinfo($host) {
    
$return = array();
    if (
preg_match('/[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}/'$host)) {
        
$ip $host;
    }
    else {
        
$ip gethostbyname($host);
        if (
$ip == $host) {
            return 
false;
        }
    }
    
$return['ip'] = $ip;
    
$return['hostname'] = gethostbyaddr($ip);
    
$lookup = @file("http://api.hostip.info/get_html.php?ip=$ip&position=true");
    if (
$lookup === false) {
        return 
false;
    }
    
$country ucfirst(strtolower(substr($lookup[0], 9, -6)));
    
$cc strtolower(substr($lookup[0], -42));
    if (
$cc != 'xx') {
        
$return['country'] = $country;
        
$return['cc'] = $cc;
        if (
trim($lookup[1]) != "City: (Unknown city)") {
            
$return['city'] = substr(trim($lookup[1]), 6);
        }
        if (
trim($lookup[2]) != "Latitude:") {
            
$return['latitude']  = substr(trim($lookup[2]), 10);
            
$return['longitude'] = substr(trim($lookup[3]), 11);
        }
    }        
    else {
        return 
false;
    }
    return 
$return;
}
?>

Last updated: Sat Jun 14 20:02:45 CEST 2008

Valid XHTML 1.0! Valid HTML 3.2!