PHP Detect User Country By IP Address

In order to detect user country we need to use an ip tool. geoiptool.com 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.

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

    if(filter_var($client, FILTER_VALIDATE_IP)){$ip = $client;}
    elseif(filter_var($forward, FILTER_VALIDATE_IP)){$ip = $forward;}
    else{$ip = $remote;}
    return $client;
}

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

    preg_match("@<span>(.*?)</span>@si",$result_html[1][2],$result);
    
    return $result[1] ;
}

How to detect user country by ip address in PHP

Leave a Reply

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