Get Current Location based on IP using PHP


<?php
if ($_SERVER[‘HTTP_CLIENT_IP’])
$ipaddress = $_SERVER[‘HTTP_CLIENT_IP’];
else if($_SERVER[‘HTTP_X_FORWARDED_FOR’])
$ipaddress = $_SERVER[‘HTTP_X_FORWARDED_FOR’];
else if($_SERVER[‘HTTP_X_FORWARDED’])
$ipaddress = $_SERVER[‘HTTP_X_FORWARDED’];
else if($_SERVER[‘HTTP_FORWARDED_FOR’])
$ipaddress = $_SERVER[‘HTTP_FORWARDED_FOR’];
else if($_SERVER[‘HTTP_FORWARDED’])
$ipaddress = $_SERVER[‘HTTP_FORWARDED’];
else if($_SERVER[‘REMOTE_ADDR’])
$ipaddress = $_SERVER[‘REMOTE_ADDR’];
else
$ipaddress = ‘UNKNOWN’;
$ip = $ipaddress;
/*$meta_tags = get_meta_tags(‘http://www.geobytes.com/IPLocator.htm?GetLocation&template=php3.txt&IPAddress=‘ . $ip) or die(‘Error getting meta tags’);
$city = $meta_tags[‘city’];*/
$response=@file_get_contents(‘http://www.netip.de/search?query=’.$ip);
               if (empty($response))
               {
                       throw new InvalidArgumentException(“Error contacting Geo-IP-Server”);
               }
               //Array containing all regex-patterns necessary to extract ip-geoinfo from page
               $patterns=array();
               $patterns[“country”] = ‘#Country: (.*?)&nbsp;#i’;
               $patterns[“state”] = ‘#State/Region: (.*?)<br#i’;
               $patterns[“town”] = ‘#City: (.*?)<br#i’;
               //Array where results will be stored
               $ipInfo=array();
               //check response from ipserver for above patterns
               foreach ($patterns as $key => $pattern)
               {
                       //store the result in array
                       $ipInfo[$key] = preg_match($pattern,$response,$value) && !empty($value[1]) ? $value[1] : ‘not found’;
               } ?>
<div class=”view_counter new_cou_p”><p>
<?php
if($ipInfo[‘town’]!=”” || $ipInfo[‘state’]!=”” || $ipInfo[‘country’]!=””){
echo ‘Current Location: ‘;
if($ipInfo[‘town’]!=””){
echo ‘<b>’.$ipInfo[‘town’].'</b>’;
}
if($ipInfo[‘state’]!=””){
echo ‘,&nbsp;&nbsp;’;
echo ‘<b>’.$ipInfo[‘state’].'</b>’;
}
if($ipInfo[‘country’]!=””){
echo ‘,&nbsp;&nbsp;’;
echo ‘<b>’.$ipInfo[‘country’].'</b>’;
}
}
?>
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s