PHP 

This tutorial will show you how we you can get Country, City, State information from an IP address using PHP. Sometimes we are curious to know the details about a user who has been visiting the web page, then we can use this kind of application to log the visitor’s details into database.

In this tutorial I am passing the IP to an external URL which will actually fetch the information and I will extract the detail information from response HTML.
Prerequisites

PHP 5.4
MySQL 5.5
Apace http Server 2.4
Netbeans 7.4 (Optional)

Step 1. Creates a php projects using Netbeans or create a project directory under htdocs.

Step 2. Create a php file called config.php with the below source code in the project directory

<?php

ini_set('display_errors', 'On');

error_reporting(E_ALL);

// setting up the web root and server root
$thisFile = str_replace('\\', '/', __FILE__);
$docRoot = $_SERVER['DOCUMENT_ROOT'];

$webRoot = str_replace(array($docRoot, 'config.php'), '', $thisFile);
$srvRoot = str_replace('config.php', '', $thisFile);

define('SRV_ROOT', $srvRoot);

require_once 'common.php';

/*
* End of file config.php
*/

Step 3. Create a common.php file with below source code in the project directory

<?php

//get city info from IP Adress
function get_country_city_from_ip($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");
        return "error";
    }

    //Array containing all regex-patterns necessary to extract ip-geoinfo from page
    $patterns = array();
    $patterns["domain"] = '#Name: (.*?)&nbsp;#i';
    $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 ip server 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;
}

/* End of file common.php */

Step 4. Create a PHP web page for displaying the Country information

<?php
require_once 'config.php';

$country_info = '';
if (isset($_POST['info'])) {
    $ip = '223.223.149.111';
    $country_info = get_country_city_from_ip($ip);
}
?>
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
<body>
    <form method="post" action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>">
        <h3>Get Country Information</h3>
        <div>
            <input type="submit" name="info" value="Get Country Info"/>
        </div>
    </form>
    <?php
    if (isset($country_info) && !empty($country_info)) {
    ?>
        <p>
        Domain : <?php echo $country_info['domain']; ?>
        </p>
        <p>
        Country : <?php echo $country_info['country']; ?>
        </p>
        <p>
        State : <?php echo $country_info['state']; ?>
        </p>
        <p>
        Town : <?php echo $country_info['town']; ?>
        </p>
    <?php
    }
    ?>
</body>
</html>

That’s all. Thanks for reading.

I am a professional Web developer, Enterprise Application developer, Software Engineer and Blogger. Connect me on JEE Tutorials Twitter Facebook  Google Plus Linkedin Or Email Me

Leave a Reply

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