Get Country information from IP address using 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.

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


ini_set('display_errors', 'On');


// setting up the web root and server root
$thisFile = str_replace('\\', '/', __FILE__);

$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


//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('' . $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

require_once 'config.php';

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

That’s all. Thanks for reading.

Leave a Comment