Geo Location Based on Ip Address - PHP

Geo Location based on IP Address - PHP

Get Geo-IP Information

Requests a geo-IP-server (netip.de) to check, returns where an IP is located (host, state, country, town).

<?php
$ip='94.219.40.96';
print_r(geoCheckIP($ip));
//Array ( [domain] => dslb-094-219-040-096.pools.arcor-ip.net [country] => DE - Germany [state] => Hessen [town] => Erzhausen )

//Get an array with geoip-infodata
function geoCheckIP($ip)
{
//check, if the provided ip is valid
if(!filter_var($ip, FILTER_VALIDATE_IP))
{
throw new InvalidArgumentException("IP is not valid");
}

//contact ip-server
$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["domain"] = '#Domain: (.*?) #i';
$patterns["country"] = '#Country: (.*?) #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';
}

return $ipInfo;
}

?>

Getting location details from IP in PHP

$ip = '98.229.152.237';
$xml = simplexml_load_file("http://ipinfodb.com/ip_query.php?ip=$ip");
print_r($xml);

Output:

SimpleXMLElement Object
(
[Ip] => 98.229.152.237
[Status] => OK
[CountryCode] => US
[CountryName] => United States
[RegionCode] => 33
[RegionName] => New Hampshire
[City] => Manchester
[ZipPostalCode] => 03103
[Latitude] => 42.9403
[Longitude] => -71.4435
[Timezone] => -5
[Gmtoffset] => -5
[Dstoffset] => -4
)

Determining user language based on IP address (geolocation)

You code returns an error: PHP Parse error: syntax error, unexpected 'default' (T_DEFAULT) in yourfile.php on line. It means that you're misusing default in switch statement. Replace your last part of your code with this:

default:
if(visitor_country() == "Germany") {
$lang_file = 'lang.de.php';
echo "Germany";
} else {
$lang_file = 'lang.en.php';
echo "Not in Germany";
}

Take out default from inside of if/else statement.

EDIT 1:

Make sure that PHP displays ERRORS, WARNING and NOTICES to properly debug your code:

ini_set('display_errors', -1);

EDIT 2:

If it was working without the switch statement, like you said, then you must make sure that files lang.en.php/lang.de.php really exist.

EDIT 3:

You are suppressing errors with having @ in-front of json_decode(file_get_contents. Most likely you would have to edit your php.ini and enable allow_url_fopen to make it work. I bet if you remove @, you will get an error:

 Warning: file_get_contents(): http:// wrapper is disabled in the server configuration by allow_url_fopen=0 in

I wouldn't strongly recommend using this kind of method to detect user language and enabling allow_url_fopen as it's possible security flaw! In case you're interested, I will provide you with much better solution for determining user browsers' language.

getCity/state from IP address using PHP

This API will get your location details. Try this

    <?php
$ip = '168.192.0.1'; // your ip address here
$query = @unserialize(file_get_contents('http://ip-api.com/php/'.$ip));
if($query && $query['status'] == 'success')
{
echo 'Your City is ' . $query['city'];
echo '<br />';
echo 'Your State is ' . $query['region'];
echo '<br />';
echo 'Your Zipcode is ' . $query['zip'];
echo '<br />';
echo 'Your Coordinates are ' . $query['lat'] . ', ' . $query['lon'];
}
?>

Here are the outputs you can use. Call them using the key;

    <?php
array (
'status' => 'success',
'country' => 'COUNTRY',
'countryCode' => 'COUNTRY CODE',
'region' => 'REGION CODE',
'regionName' => 'REGION NAME',
'city' => 'CITY',
'zip' => 'ZIP CODE',
'lat' => 'LATITUDE',
'lon' => 'LONGITUDE',
'timezone' => 'TIME ZONE',
'isp' => 'ISP NAME',
'org' => 'ORGANIZATION NAME',
'as' => 'AS NUMBER / NAME',
'query' => 'IP ADDRESS USED FOR QUERY',
);
?>

This will not be reliable for mobile. If you are on mobile, you can use the following javascript

    <script>
var x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
</script>

This will use the gps built in to the device and get the cordinates. Then you can cross reference with a database filled with cords. (thats one option, and thats what i do).

You can find a city lat lng databases online if you search and if thats what you chose to do for mobile.



Related Topics



Leave a reply



Submit