How do you detect a website visitor's country (Specifically, US or not)?

前端 未结 8 2022
無奈伤痛
無奈伤痛 2020-12-12 19:11

I need to show different links for US and non-US visitors to my site. This is for convenience only, so I am not looking for a super-high degree of accuracy, and security or

8条回答
  •  一向
    一向 (楼主)
    2020-12-12 19:59

    @rostislav

    or using cURL:

    public function __construct($site_name) {
        // create a new cURL resource
        $ch = curl_init();
    
        // set URL and other appropriate options
        curl_setopt($ch, CURLOPT_POST, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, Array("Content-Type: text/xml"));
        curl_setopt($ch, CURLOPT_URL, "http://api.wipmania.com".$_SERVER['REMOTE_ADDR']."?".$site_name);
        curl_setopt($ch, CURLOPT_HEADER, 0);
    
        // grab URL and pass it to the browser
        $response = curl_exec($ch);
        $info = curl_getinfo($ch,CURLINFO_HTTP_CODE);
    
        if (($response === false) || ($info !== 200)) {
            throw new Exception('HTTP Error calling Wipmania API - HTTP Status: ' . $info . ' - cURL Erorr: ' . curl_error($ch));
        } elseif (curl_errno($ch) > 0) {
            throw new Exception('HTTP Error calling Wipmania API - cURL Error: ' . curl_error($ch));
        }
    
        $this->country = $response;
    
        // close cURL resource, and free up system resources
        curl_close($ch);
    }
    

提交回复
热议问题