Ip location finder - php

I want to find the location (country, city,..) of my site visitor by their IP.
I'm coding php.
who can help me?
something like this:
$url = json_decode(file_get_contents("http://api.ipinfodb.com/v3/ip-city/?key=/*userapikey*/
ip=".$_SERVER['REMOTE_ADDR']."&format=json"));
$country=$url->countryName; // user country
$city=$url->cityName; // city
$region=$url->regionName; // regoin
$latitude=$url->latitude; //lat and lon
$longitude=$url->longitude;

Seems there is a & missing in the URL:
$url = json_decode(file_get_contents("http://api.ipinfodb.com/v3/ip-city/?key=/*userapikey*/&ip=".$_SERVER['REMOTE_ADDR']."&format=json"));
Probably, you should encode the IP:
$url = json_decode(file_get_contents("http://api.ipinfodb.com/v3/ip-city/?key=/*userapikey*/&ip=".urlencode($_SERVER['REMOTE_ADDR'])."&format=json"));
Then you can do this to get information about the result:
var_dump($url);
If you have another problem, please write it to the question.

Have a look at freegeoip.net. It's a webservice that gives you exactly the data you need for a specific IP.
E.g.:
https://freegeoip.net/json/1.2.3.4
will give you this JSON data:
{
ip: "1.2.3.4",
country_code: "US",
country_name: "USA",
region_code: "WA",
region_name: "Washington",
city: "Mukilteo",
zip_code: "98275",
time_zone: "America/Los_Angeles",
latitude: 47.945,
longitude: -122.305,
metro_code: 819
}

Check out https://freegeoip.net/. They offer a free API for up to 10,000 searches per hour.
Example:
$res = json_decode(file_get_contents("https://freegeoip.net/json/109.80.75.20"));
$countryCode = $res->country_code;
$country = $res->country_name;

Related

Get country name from google maps in php

I have user Ip address. i want country name of that user. I don't want to use geoIp(plugin) so is there any way to get country name from google maps without JS support(send country name through ajax is not option) in php ?
Without JS yes you can be able,but still you need to use geo-plugin. You can use one from this site http://www.geoplugin.com/
<?php
$ip = "41.164.194.81";
$geo = unserialize(file_get_contents("http://www.geoplugin.net/php.gp?ip=$ip"));
$country = $geo["geoplugin_countryName"];
// $city = $geo["geoplugin_city"]; if you need the city as well
echo $country;
?>
Results :
South Africa
Google API doesn't have any API related to IP reverse or IP location (as far as I know of)
You can use other free website if you want to.
You can use https://freegeoip.net/json/78.194.1.99, it's free and the limit is set to 10000 calls / hours.
Code:
<?php
$ip = '78.194.1.99';
$data = #json_decode(file_get_contents('https://freegeoip.net/json/' . $ip));
$country = $data->country_name;
JSON Result:
{
"ip": "78.194.1.99",
"country_code": "FR",
"country_name": "France",
"region_code": "IDF",
"region_name": "Île-de-France",
"city": "Paris",
"zip_code": "75009",
"time_zone": "Europe/Paris",
"latitude": 48.8718,
"longitude": 2.3399,
"metro_code": 0
}
By the way, why you don't want to use a geo plugin ?

Google Maps API with PHP to find distance between two locations

On my current project, which is a delivery system, I have a list of available delivery drivers, which is shown on an orders page. But what I need is to show the distance each delivery is from the customers address. The distance should be shown next to each driver's name. Anyone have any clues on how I would go about this?
Assuming that you want driving distance and not straight line distance, you can use the Directions web service:
You need to make an http or https request from your PHP script and the parse the JSON or XML response.
Documentation:
https://developers.google.com/maps/documentation/directions/
For example:
Boston,MA to Concord,MA via Charlestown,MA and Lexington,MA (JSON)
http://maps.googleapis.com/maps/api/directions/json?origin=Boston,MA&destination=Concord,MA&waypoints=Charlestown,MA|Lexington,MA&sensor=false
Boston,MA to Concord,MA via Charlestown,MA and Lexington,MA (XML)
http://maps.googleapis.com/maps/api/directions/xml?origin=Boston,MA&destination=Concord,MA&waypoints=Charlestown,MA|Lexington,MA&sensor=false
Note that there are usage limits.
You can easily calculates the distance between two address using Google Maps API and PHP.
$addressFrom = 'Insert from address';
$addressTo = 'Insert to address';
$distance = getDistance($addressFrom, $addressTo, "K");
echo $distance;
You can get the getDistance() function codes from here - http://www.codexworld.com/distance-between-two-addresses-google-maps-api-php/
this will out seconds between 2 location
$origin =urlencode('Optus Sydney International Airport, Airport Drive, Mascot NSW 2020, Australia');
$destination = urlencode('Sydney NSW, Australia');
$url = "https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=$origin&destinations=$destination&key=your_key";
$data = #file_get_contents($url);
$data = json_decode($data,true);
echo $data['rows'][0]['elements'][0]['duration']['value'];

Map cities of UK onto postcodes

I was wondering if anyone is aware of any PHP scripts which maps a UK City onto a Post Code.
I have found something like this:
case'North West England, England': {
$postcode = 'M1 2NQ';
break;
}
case'North East England, England': {
$postcode = 'NE1 6AD';
break;
}
case'South West England, England': {
$postcode = 'EX1 3AX';
break;
}
But it only covers areas as you can see, rather than cities such as 'Manchester, Edinburgh' etc.
Any input would be greatly appreciated.
Thanks,
AP
You might think of using Google Map API
You can use the ONS Postcode Directory (ONSPD). You'd have to set up a database and import all the data, then build your application round it.

PHP & API for IP Geolocation

I am trying to use http://www.hostip.info/use.html in my web app to show the approximate City location of an IP address. I cannot figure out how to actually show the contents of the API... Here is what I have that is not working.
function showCity($currIP){
$lookupData = 'http://api.hostip.info/get_html.php?ip='.$currIP;
return $lookupData;
}
Your API returns this:
Country: UNITED STATES (US)
City: Seattle, WA
IP: 168.111.127.225
So you need to do some string parsing on that result. Using the below will get your started:
$array = preg_split('/$\R?^:/m', $lookupData);
print_r($array);
Try this instead:
$array = preg_split("/[\r\n]/", $lookupData, -1, PREG_SPLIT_NO_EMPTY);
Also, as was mentioned by mcmajkel, if you use the JSON api link, you can get to it with this:
$lookupData = 'http://api.hostip.info/get_json.php?ip='.$currIP;
$api = json_decode($lookupData);
$myName = $api->country_name;
$myCode = $api->country_code;
$myCity = $api->city;
$myIP = $api->ip;
This call returns string, as mentioned by GregP. But you can call
http://api.hostip.info/get_json.php?ip=12.215.42.19
And get a nice piece of JSON in return, which will be easier to
parse

PHP IF Statment Based On Geo Location?

Is there a way to do a PHP If statement based on the persons location?
My problem comes down to Amazon Affiliate links. The link to buy a DVD on Amazon.co.uk is different to the one to buy from Amazon.com and I want a way to only show the correct one.
At the same time, If they aren't based in either country, then I don't want the link to show in the first place.
Example:
If Location = UK; print "amazon-UK-link"
If Location = US; print "amazon-US-link"
If location = None of the above; print nothing
You can use: string geoip_country_code_by_name ( string $hostname )
Example:
<?php
$country = geoip_country_code_by_name('www.example.com');
if ($country) {
echo 'This host is located in: ' . $country;
}
?>
Output:
This host is located in: US
For your case you can use: geoip_country_code_by_name($_SERVER['REMOTE_ADDR']); to get the country code for the current user.
You're going to have to use the visitor's IP address to lookup their physical location. Apart from using the GeoIP extension for PHP (as stewe pointed out), there are two ways of doing this:
The easy way
Use an external service like http://www.hostip.info
With your own MySQL data
1.) Retrieve the visitors' IP address:
if (getenv('HTTP_X_FORWARDED_FOR'))
{
$ip_address = getenv('HTTP_X_FORWARDED_FOR');
}
else
{
$ip_address = getenv('REMOTE_ADDR');
}
2.) Convert the visitor's IP address to an IP Number:
$ips = explode(".",$ip_address);
return ($ips[3] + $ips[2] * 256 + $ips[1] * 256 * 256 + $ips[0] * 256 * 256 * 256);
3.) Locate the IP Number from your database which you can download here.
For example: the IP Address 202.186.13.4 converts to IP Number 3401190660. It is between the beginning and the ending of the following IP numbers:
Beginning_IP | End_IP | Country | ISO
-------------+-------------+----------+----
3401056256 | 3401400319 | MALAYSIA | MY
You need to use geoip for that by maxmind http://www.maxmind.com/app/ip-location or there's another option, search for an IP to Country API, there some on the web.
You can use a simple API from http://www.geoplugin.net/
$xml = simplexml_load_file("http://www.geoplugin.net/xml.gp?ip=".getRealIpAddr());
echo $xml->geoplugin_countryName ;
echo "<pre>" ;
foreach ($xml as $key => $value)
{
echo $key , "= " , $value , " \n" ;
}
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;
}
Output
United States
geoplugin_city= San Antonio
geoplugin_region= TX
geoplugin_areaCode= 210
geoplugin_dmaCode= 641
geoplugin_countryCode= US
geoplugin_countryName= United States
geoplugin_continentCode= NA
geoplugin_latitude= 29.488899230957
geoplugin_longitude= -98.398696899414
geoplugin_regionCode= TX
geoplugin_regionName= Texas
geoplugin_currencyCode= USD
geoplugin_currencySymbol= $
geoplugin_currencyConverter= 1
It makes you have so many options you can play around with
Thanks
:)

Categories