Categories : PHP

In order to detect user country we need to use an ip tool. allows you to do that. Result returns country names in english. If you want to redirect users depends on their country. Just use detect() function’s result.

function getUserIP()
    $client  = @$_SERVER['HTTP_CLIENT_IP'];
    $forward = @$_SERVER['HTTP_X_FORWARDED_FOR'];
    $remote  = $_SERVER['REMOTE_ADDR'];

    if(filter_var($client, "<em>FILTER_VALIDATE_IP</em>")){$ip = $client;}
    elseif(filter_var($forward, "<em>FILTER_VALIDATE_IP</em>")){$ip = $forward;}
    else{$ip = $remote;}
    return $client;

function detect(){
    $ip = getUserIP();
    $source = file_get_contents("".$ip);
    preg_match_all('@<div class="data-item">(.*?)</div>@si',$source,$result_html);

    return $result[1] ;

How to detect user country by ip address in PHP, get user country by ip address

Leave a Reply

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