Getting country , city name from IP address in PHP

Advertisement

Yesterday, miaki asked me how can we get the country name from the IP address in PHP. Today, I’ve come up with the answer of this question. I’ve used the API from hostip.info to fetch the country name , city name and country code from the given IP address. I’ve mad this function in PHP which uses XML response from hostip.info and extracted country name, city name and country code using regular expression.

Function to return country, city name from IP address in PHP

function countryCityFromIP($ipAddr)
{
//function to find country and city from IP address
//Developed by Roshan Bhattarai http://roshanbh.com.np

//verify the IP address for the
ip2long($ipAddr)== -1 || ip2long($ipAddr) === false ? trigger_error("Invalid IP", E_USER_ERROR) : "";
$ipDetail=array(); //initialize a blank array

//get the XML result from hostip.info
$xml = file_get_contents("http://api.hostip.info/?ip=".$ipAddr);

//get the city name inside the node <gml:name> and </gml:name>
preg_match("@<Hostip>(\s)*<gml:name>(.*?)</gml:name>@si",$xml,$match);

//assing the city name to the array
$ipDetail['city']=$match[2]; 

//get the country name inside the node <countryName> and </countryName>
preg_match("@<countryName>(.*?)</countryName>@si",$xml,$matches);

//assign the country name to the $ipDetail array
$ipDetail['country']=$matches[1];

//get the country name inside the node <countryName> and </countryName>
preg_match("@<countryAbbrev>(.*?)</countryAbbrev>@si",$xml,$cc_match);
$ipDetail['country_code']=$cc_match[1]; //assing the country code to array

//return the array containing city, country and country code
return $ipDetail;

}

Download Source Code

As you can see, I’ve documented all the PHP code and I don’t think I need explain anymore about that code. Just notice that, this function returns the array containg three key elements “country” , “city” and “country_code”. Each elements have the value of city, country and country code.

Now, look the the how we can use the above function in PHP,

$IPDetail=countryCityFromIP('12.215.42.19');
echo $IPDetail['country']; //country of that IP address
echo $IPDetail['city']; //outputs the IP detail of the city

Notice that the above PHP function returns the array containing the country , city and country code from IP Address and we can use them in PHP. If you want to know how to get IP address in PHP, you can check this post how you can get real IP address in PHP.

Enter your email address and get free tutorials, tips and tricks of PHP, Ajax, JavaScript and CSS directly delivered to you email inbox:

48 Comments on “Getting country , city name from IP address in PHP”

  • subesh wrote on 17 July, 2008, 11:31

    Yeha…..you can get some more of this on http://subesh.com.np/2008/07/mapping-the-ip-address-to-latitude-and-longitude-in-google-maps/

  • brsyuksel wrote on 18 July, 2008, 8:43

    http://hido.net/ip2country.txt
    http://hido.net/ip2country.phps

    ;) It can output only Country name but running on your server. You don’t need other service. ( Sorry my bad english :) )

  • Roshan wrote on 18 July, 2008, 9:39

    @brsyuksel …thanks for sharing that with us…

  • Krasimir Kazakov wrote on 18 July, 2008, 12:45

    This one is better

    http://www.maxmind.com/download/geoip/api/php/

  • Hugh Fletcher wrote on 18 July, 2008, 15:30

    I wrote a script a while back using the html that hostip returned, thanks for the easy read on an xml version. For those that find hostip.info returns inaccurate info, I suggest http://maxmind.com as an very accurate but pay alternative.

  • Roshan wrote on 18 July, 2008, 15:38

    @Krasimir – You’ve to pay some bucks to maxmind for more accurate information retrieval

  • Someone wrote on 18 July, 2008, 17:26

    This /isn’t/ using php to derive country names. This is only a method of parsing xml using php for a site that may or may not be operational tomorrow. I’d see this as a fairly temporary solution, at best.

  • Roshan wrote on 19 July, 2008, 4:58

    @someone – yes this a only method to consume the web services using PHP and this is the best free option you can get in internet to find the city and country from IP using PHP.

    For reliability you can purchase the expensive database and use it in your application.

  • Shakeel Shrestha wrote on 20 July, 2008, 7:13

    Our college IP in Pokhara is 202.79.63.59
    When I run this script using this IP, it shows Hydrabad, India…..

    College get the internet from wlink, pokhara center.

    Why is it so?

  • Roshan wrote on 20 July, 2008, 8:35

    ya seems that their API is returning wrong value for this ip address 202.79.63.59. Hostip.info is returning Hydarabad, India but when I checked the same from ip2location.com it is showing it is from Nepal.

    http://www.ip2location.com/202.79.63.59

  • Hem wrote on 21 July, 2008, 4:27

    I have done some this and that to show country , browser info and OS ( plugins ) in comment list .this one is good too

  • seb wrote on 21 July, 2008, 5:46

    Yeah the problem with this approach is that the API looks up the location of the company that owns the netblock, or so it seems.

    The city/province returned when I look up my cable modem is the city/province where my ISP is headquartered (and that’s not where I am, it’s in a different province elsewhere in the country).

    Not super useful.

  • Roshan wrote on 21 July, 2008, 9:40

    It’s not the fault of their API if you’re sending wrong IP address. $_SERVER['REMOTE_ADDR'] always returns the IP address of proxy server not the IP address of the computer.

    You better have to get the HTTP_X_FORWARDED_FOR and HTTP_CLIENT_IP header values…

    hope this helps

  • stratosg wrote on 23 July, 2008, 17:57

    this is a nice find and script. the inaccuracy may be also caused because their database can be a bit old…

  • maya wrote on 31 July, 2008, 2:12

    Hello it was a great article and i like your blog! keep up the good work…

  • Ireland web z wrote on 3 August, 2008, 21:21

    Hi, i’m programing dating site and this is cool working script. Combined with get real ip – amazing. Great job. Thank you!!!

  • Alex wrote on 7 August, 2008, 11:11

    Hi,

    Ok, we found the details about ip address, can any help me to know about the mechine(computer name) name using ip

  • Roshan wrote on 7 August, 2008, 17:01

    for this you can use gethostbyaddr() function of PHP

  • Max wrote on 12 September, 2008, 8:12

    Very good post . See http://mywebservice.fr because it’s propose a lot of good webservices ;)

  • riya wrote on 7 October, 2008, 10:23

    Hi Roshan..

    Nice script.. but how we can rectify the problem of
    Shakeel Shrestha

  • Roshan wrote on 12 October, 2008, 6:43

    @riya – it is due to their inaccurate database we need to ask them to update this…and if you want accurate result then you can try http://maxmind.com but you’ve to pay some money for using the service

  • Bill Conner wrote on 18 October, 2008, 22:01

    You insert an explicit numeric IP address in the countryCityFromIP(‘66.96.134.24′). I get errors when I use a variable. Not being a PHP expert, this is confusing and I get errors no matter whatever I use. So, how do I use an address derived from the script?

  • Vin wrote on 26 November, 2008, 22:33

    How can I get the zip code instead of the city?

  • Music wrote on 28 November, 2008, 8:15

    thanks for the post very useful

  • Venu wrote on 19 January, 2009, 7:45

    Hi Roshan,

    How can i find the international dialling prefix based on IP?

  • Geni wrote on 27 January, 2009, 19:09

    Great! Does anybody know if there are restrictions for using this type of service. As it is free I suppose it has its limitations!

  • Krishan wrote on 27 February, 2009, 6:51

    Does this work now?

  • Vikas wrote on 18 March, 2009, 10:44

    Hi Roshan,

    Thanks for the script.
    I have another doubt here. You are making use of webservice to get the country name. Now suppose tomorrow, if the service provides changes the host name or if they stop providing the details, then we will not be able to get the details. Can we rely on the host name (http://api.hostip.info/?ip=) through which you are getting the details ?

    Thanks

  • Tim wrote on 13 April, 2009, 8:44

    You can get the free API from http://www.ip2location.com. It is more accurate that the free API at hostip as we’ve tested for some times.

  • Olaf wrote on 20 April, 2009, 19:48

    Hi

    does not seem to work when it’s not allowed to include /open a file from a different server.

    Olaf

  • venkat20 wrote on 22 April, 2009, 6:56

    I have found the Ip details for my home network on the site named as http://www.ip-details.com.It is very useful for me .I found the comnection speed like the uploadind speed,downloadind speed etc on the same website ,Domain name given means it will display the address of the ip server where it is located etc ..I want to know that all from the website above mentioned …another thing is it will display the map if the search loaction u have entered on search ..

  • Noor Khan wrote on 27 April, 2009, 14:42

    yaaaaaaaaar

    it’s not working on my site say unknown City??

  • IMF wrote on 9 June, 2009, 16:35

    Very good one, thanks.

  • M Rahmad wrote on 27 June, 2009, 6:27

    I try to test it on my sites. I try it via localhost. But, why doesn’t it work?

  • raj wrote on 4 November, 2009, 10:25

    HI roshan ,

    I m from hyderabad india i m not able to get the zip code other than this i can get the country name city name every thing works fine is this issue with the only city from india or other countries also face the same problem? as i m facing problem by not retriving the IPaddress

    Thanks

  • Morris wrote on 31 January, 2010, 0:39

    Hey mate, thanks for the script.

    However, I’m having trouble getting it going. I’m fairly inexperienced with php, so please bear with me.

    In the code you have a placeholder IP that generates the location, etc. What do I replace this with to generate the IP ??

  • Anand kumar wrote on 5 February, 2010, 14:27

    HI!
    I need to get US and UK all cities with IP. I tried with this but most of the UK cities are Unknown type and unknow city. will you help to solve my problem.

    Hope to here reply from you dear.

    Thanks,
    Anand.

  • blub design wrote on 10 March, 2010, 12:41

    I’m only getting country and code, but not city. why?

  • senthil wrote on 23 March, 2010, 20:06

    thanks for sharing that with us, this will be useful to me.
    domainhostlowprice.com

  • PHP Programmer wrote on 2 April, 2010, 4:29

    Thanks these are some great resources to start..

  • Malay Mehta wrote on 28 April, 2010, 11:29

    Hi Roshan,
    Thanks again for the wonderful work.

    I have learnt a lot from you and your snippets.

    Thanks

  • Joko wrote on 7 August, 2010, 18:15

    Thanks for the code. I got it working with the country. Not the city. I think they changed the XML markup.

    Thanks again for the code!

  • adnan zulkarnain wrote on 8 August, 2010, 0:56

    hi roshan,

    how to getting city?

  • Manoj Dalui wrote on 16 September, 2010, 12:17

    I want to display zip/postal code like city and country .How is it possible from this above code

  • ABC Plugin Review wrote on 8 February, 2011, 20:11

    THis is a great little script – thank you very much for sharing it. Really looking forward to trying it out,

    Thanks again, Steve

  • Vincent wrote on 13 February, 2011, 13:22

    hi roshan,
    I can’t get city name too, could you help me ?

Trackbacks

  1. PHP : Get country by ip | kzzen.com | Webmaster Blog
  2. links for 2009-03-03 « Page 2

Write a Comment

 


Copyright © 2014 Roshan Bhattarai's Blog. All rights reserved.
Powered by WordPress.org, Custom Theme and ComFi.com Calling Card Company.