Getting the client[Client Browser] ip, country and city Using php


     Normally,  Web application owner  wanted have  the  client details either for the  security reason and for the  analysis purpose.   


First, getRealIpAddr()  function to  get IP address from the  client [user Browser]

 function getRealIpAddr()
{
                 if (!empty($_SERVER['HTTP_CLIENT_IP']))   //check ip from share internet
               {
                              $ip=$_SERVER['HTTP_CLIENT_IP'];
               }
               elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))   //to check ip is pass from proxy
               {
                              $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
               }
               else
               {
                              $ip=$_SERVER['REMOTE_ADDR'];
               }
               return $ip;
}


After getting the  IP  Address ,  we  can  easily find  out the  city  and  country  of the  client  browser  by  passing the  ip  address  to  the  function. In the  get_location() function , I  use  the  http://api.hostip.info API. hostip  is the free one  and  no  need to  register.


function get_location($ip) {
               $content = @file_get_contents('http://api.hostip.info/?ip='.$ip);
               if ($content != FALSE) {
                              $xml = new SimpleXmlElement($content);
                              $coordinates = $xml->children('gml', TRUE)->featureMember->children('', TRUE)->Hostip->ipLocation->children('gml', TRUE)->pointProperty->Point->coordinates;
                              $longlat = explode(',', $coordinates);
                              $location['longitude'] = $longlat[0];
                              $location['latitude'] = $longlat[1];                           
                               $location['city'] = ''.$xml->children('gml', TRUE)->featureMember->children('', TRUE)->Hostip->children('gml', TRUE)->name;
                              $location['country'] =  ''.$xml->children('gml', TRUE)->featureMember->children('', TRUE)->Hostip->countryName;
                              return $location;
               }
               else return false;
}


Finally  the output,   we can change  formate  of the output based on the  requirement.


$ip = getRealIpAddr();
$location_info = get_location($ip);
echo $location_info['country']."</br/>";
echo $location_info['city'];


i  appreciate  your  comments

No comments:

Post a Comment