Yii 1.1: Find geolocation info of client through another API

3 followers

This wiki shows how to get the geolocation info of the client using another server API It could be write also as extension but there are a lots of APIs that change the below code So, I wrote the below code that works for one of them (using www.geoplugin.net)

Add the file Geolocation.php in protected/components

class Geolocation {
 
    public static $ipaddress = null;
    public static $clientInfoLocation = null;
 
 
    public static function get_client_ip() {
        if (self::$ipaddress == null) {
            if (isset($_SERVER['HTTP_CLIENT_IP']))
                $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
            else if (isset($_SERVER['HTTP_X_FORWARDED_FOR']))
                $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
            else if (isset($_SERVER['HTTP_X_FORWARDED']))
                $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
            else if (isset($_SERVER['HTTP_FORWARDED_FOR']))
                $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
            else if (isset($_SERVER['HTTP_FORWARDED']))
                $ipaddress = $_SERVER['HTTP_FORWARDED'];
            else if (isset($_SERVER['REMOTE_ADDR']))
                $ipaddress = $_SERVER['REMOTE_ADDR'];
            else
                $ipaddress = '127.0.0.1';
        }
        return self::$ipaddress;
    }
 
    public static function getClientInfoLocation() {
        if (self::$clientInfoLocation == null)
            self::$clientInfoLocation = (unserialize(file_get_contents('http://www.geoplugin.net/php.gp?ip=' . self::get_client_ip())));
        return self::$clientInfoLocation;
    }
 
    public static function getClientCountry() {
        $dt = self::getClientInfoLocation();
        return strtolower($dt['geoplugin_countryName']);
    }
 
    public static function getClientLangCode() {
        $dt = self::getClientInfoLocation();
        return strtolower($dt['geoplugin_countryCode']);
    }
 
}

Now, In any controller you chould use Geolocation::getClientCountry() or Geolocation::getClientLangCode()

Be the first person to leave a comment

Please to leave your comment.

Write new article