Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Get Country By IP Address in PHP

DZone's Guide to

Get Country By IP Address in PHP

· Web Dev Zone
Free Resource

Get deep insight into Node.js applications with real-time metrics, CPU profiling, and heap snapshots with N|Solid from NodeSource. Learn more.

 This simple function allows you to getect a country code and city of your site visitors, using the www.geoplugin.net service. You may use this data to add default values in registration form or use it for any other purposes, like blocking access to your site from special regions.

Source: http://www.apphp.com/index.php?snippet=php-get-country-by-ip

function getLocationInfoByIp(){
    $client  = @$_SERVER['HTTP_CLIENT_IP'];
    $forward = @$_SERVER['HTTP_X_FORWARDED_FOR'];
    $remote  = @$_SERVER['REMOTE_ADDR'];
    $result  = array('country'=>'', 'city'=>'');
    if(filter_var($client, FILTER_VALIDATE_IP)){
        $ip = $client;
    }elseif(filter_var($forward, FILTER_VALIDATE_IP)){
        $ip = $forward;
    }else{
        $ip = $remote;
    }
    $ip_data = @json_decode(file_get_contents("http://www.geoplugin.net/json.gp?ip=".$ip));    
    if($ip_data && $ip_data->geoplugin_countryName != null){
        $result['country'] = $ip_data->geoplugin_countryCode;
        $result['city'] = $ip_data->geoplugin_city;
    }
    return $result;
}

Node.js application metrics sent directly to any statsd-compliant system. Get N|Solid

Topics:
php

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}