Find visitor’s country using his ip address

I have created a small php class that parses the IP2country.csv file and finds the visitor’s country using his ip address.

Installations:

First download the latest ip address database from http://software77.net/geo-ip/
In right sidebar you will see Download, Select IPV4 CSV (gz). Here you can also download .zip file
Then download the file.
Place the file in the same folder where this script is.

Note:You can also change the file location of IpToCountry.csv just pase this file location to parseCsv() function.

And then

1. include the ip2address.php

require “ip2address.php”;
2. Create a new object of IP2Country
$ip = new IpToCountry($client_ip);
3. call the parseCSV
$ip->parseCsv();
4. to get country name
$ip->getCountryName()
5. to get country code
$ip->getCountryCode()
6. Just for debug purpose use
echo $ip;
7. That’s it, enjoy.
8. If you use this class just let me know through comment.

If you find any bug please report it to me.

The class is IpToCountry and can be used the following way.

<?php
require 'ip2address.php';
$client_ip = '202.166.217.94';

$ip = new IpToCountry($client_ip);
$ip->parseCsv();
echo $ip;

?>

Download the zipped version from http://www.samundra.com.np/downloads/ip2address.zip

ip2address.zip contains the following files
ip2address.php- This file contains the main class sourcecode
test.php – This file contains the test code.
README.txt – How to use this class file and just replica of this article or Documentation.

Samundra Shrestha

Fullstack Developer, Senior Software Engineer

6 thoughts on “Find visitor’s country using his ip address

  • June 30, 2014 at 11:35 AM
    Permalink

    There no code in zip file
    page not found error

    Reply
    • July 4, 2014 at 8:45 AM
      Permalink

      I have migrated my server and have possibly broken the link. I will fix it soon and let you know. As I am currently in the middle of something and can’t fix it.

      Thanks

      Reply
  • May 7, 2013 at 8:00 AM
    Permalink

    The link you provide to ip2address.zip is giving a ‘404’ error.

    Reply
  • January 3, 2013 at 10:07 AM
    Permalink

    Hi sumandra,

    The link you provide to ip2address.zip is giving a ‘404’ error. Do you have an up-to-date URL where I could download it?

    Many thanks,
    Ady

    Reply
    • June 30, 2014 at 11:36 AM
      Permalink

      Yes I agree

      Reply

Leave a Reply

Your email address will not be published. Required fields are marked *