Fastest Way Of Detecting User's Country

吃可爱长大的小学妹 提交于 2019-11-30 14:16:00

问题


I need detect user's country and show website's language by him / her country . (Turkish for Turkish people, English for all others)

How can i do this fastest way ? Performance is important for me .

I'm looking IPInfoDB' API , are there any better alternative ?

(I'm using PHP)


回答1:


Well for people who might visit in 2017 this is a solution this extremely simple to use

<button class="btn dropdown-toggle" style="cursor:pointer;z-index:1000!important;margin-top:-67px;background:none!important;font-size:1.4em;" onclick="window.location.href='language'">
(a)  <?php
if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
$ip = $_SERVER['HTTP_CLIENT_IP'];}
elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
$ip = $_SERVER['REMOTE_ADDR'];
}
$url = "http://api.wipmania.com/".$ip;
(h) $country = file_get_contents($url); //ISO code for Nigeria it is NG check your country ISO code
?>

<?php if ($country == ""){
echo "Country not found";   
} else { ?>
<script>
var map = "<?php echo $country ?>";
$.ajax({
type : 'POST', 
url : 'http://www.mowemy.com/countryflag.php',
data :  {map: map}, 
success : function(r) { 
//console.log("success: " + r); 
$('#mumil').html(r); 
} })
</script>
<?php } ?>

<div id ="mumil" style="font-size:13px!important;margin-top:5px;"></div>
</button>

let me beak it down letter A - H is the script to detect your ISO number for the country for my country Nigeria it is NG you can google search your countries ISO number, with this script it is auto detected. Then i created a page with some info you fire AJAX to that page which it sends back the country flag color and name simple and easy PLEASE CALL JQUERY BEFORE AJAX TO RUN THE AJAX UNLESS IT WONT WORK GOODLUCK




回答2:


You could use the API here http://www.hostip.info/use.html if you're okay with relying on an external site.

You can also use the GeoIP PHP API

Of course, implementing the script Orbit linked might just save you the hassle of going through the API's.

Good luck.




回答3:


The best way to do this I have found is using the "GAE-IP-TO-COUNTRY" library: https://github.com/andris9/GAE-IP-TO-COUNTRY/tree/master/src/ip_files

Example of use (you have to copy the "ip_files" directory to your server):

function iptocountry($ip) {    
    $numbers = preg_split( "/\./", $ip);    
    include("./ip_files/".$numbers[0].".php");
    $code=($numbers[0] * 16777216) + ($numbers[1] * 65536) + ($numbers[2] * 256) + ($numbers[3]);    
    foreach($ranges as $key => $value){
        if($key<=$code){
            if($ranges[$key][0]>=$code){$country=$ranges[$key][1];break;}
        }
    }
    return $country;
}

$country=iptocountry($_SERVER['REMOTE_ADDR']);
echo $country;



回答4:


As others have pointed out, it would probably a better idea to check the Accept-Language HTTP Header for Turkish. If it's the preferred language, serve it. Otherwise serve English. Here's some code.




回答5:


I coded the next stuff using Accept-Language as other users pointed:

function GetAcceptedLangs()
{
    $res=array();
    $a=getallheaders();
    if(isset($a["Accept-Language"]))
    {
        $aceptlangs=explode(",",str_replace(array(';','0','1','2','3','4','5','6','7','8','9','.',"q="),array(',','','','','','','','','','','','',""),$a["Accept-Language"]));
        foreach($aceptlangs as $i=>$v)
        {
            if(trim($v)!="")
                $res[]=trim($v);
        }
    }
    return $res;
}

A simple

print_r(GetAcceptedLangs());

return in my case:

Array ( [0] => es-ES [1] => es [2] => en )

You can after define an array like this one to change to your internal language value, for example:

$al={"ES-es"=>"es","es"=>"es","en"=>"en"......}

They are already sorted by user preferences.

If all languages don't exists in the array you can go to the default language of your website. This is valid also if the browser don't send the Accept-Language header.

Another version removing the sub-region values

function GetAcceptedLangs2()
{
    $res=array();
    $a=getallheaders();
    if(isset($a["Accept-Language"]))
    {
        $aceptlangs=explode(",",str_replace(array(';','0','1','2','3','4','5','6','7','8','9','.',"q="),array(',','','','','','','','','','','','',""),$a["Accept-Language"]));
        foreach($aceptlangs as $i=>$v)
        {
            $va=trim($v);
            if(($pos=strpos($va,"-"))!==false)
                $l=substr($va,0,$pos);
            else
                $l=$va;
            if($l!="" && !isset($check[$l]))
            {
                $check[$l]=1;
                $res[]=$l;
            }
        }
    }
    return $res;
}

It would return in my case

Array ( [0] => es [1] => en )



回答6:


Here is the straight forward way I like to use

<?php
class GeoIp
{
    protected $api = 'https://ipapi.co/%s/json/';

    protected $properties = [];

    //------------------------------------------------------
    /**
    *   __get
    *
    * @access public
    * - @param $key string
    * - @return string / bool
    */  
    public function __get($key)
    {
        if( isset($this->properties[$key]))
        {
            return $this->properties[$key];
        }

        return null;
    }

    //------------------------------------------------------
    /**
    *   request_geoip
    *
    * @access public
    * - @return void
    */
    public function request_geoip($ip)
    {
        $url = sprintf($this->api, $ip);
        $data = $this->send_geoip_request($url);
        $this->properties =  json_decode($data, true);
        //var_dump($this->properties);
    }

    //------------------------------------------------------
    /**
    *   send_geoip_request
    *
    * @access public
    * - @param $url string
    * - @return json
    */
    public function send_geoip_request($url)
    {
        $loc_content = file_get_contents($url); 

        return $loc_content;
    }
}

//You can access it like this:
$geo = new GeoIp;
$geo->request_geoip('foo');
echo $geo->country;

?>

Visit this website for more info



来源:https://stackoverflow.com/questions/5206015/fastest-way-of-detecting-users-country

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!