Определение Города по IP адресу

Обсуждение документации. Переводы Cookbook и авторские рецепты.
Ответить
cezar
Сообщения: 2
Зарегистрирован: 2011.10.05, 03:00

Определение Города по IP адресу

Сообщение cezar »

Сам недавно столкнулся с данной задачей вот если кому нужно
в контреллере создаем акшен называем как хотим

Код: Выделить всё


    public function ActionGet_ip_info($ip = null) {

        $postData = "
        <ipquery>
            <fields>
                <all/>
            </fields>
            <ip-list>
                <ip>$ip</ip>
            </ip-list>
        </ipquery>
    ";

        $curl = curl_init();

        curl_setopt($curl, CURLOPT_URL, 'http://194.85.91.253:8090/geo/geo.html');
        curl_setopt($curl, CURLOPT_POSTFIELDS, $postData);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

        $responseXml = curl_exec($curl);
        curl_close($curl);

        if (substr($responseXml, 0, 5) == '<?xml') {
            $ipinfo = new SimpleXMLElement($responseXml);
            //echo $ipinfo->ip->city; // город
            //echo $ipinfo->ip->region; // регион
            //echo $ipinfo->ip->district; // федеральный округ РФ     
            return $ipinfo->ip;
        }
        return false;
    }

вставляем где необходимо вызов функции и получаем xml объект

Код: Выделить всё

$ip_info = $this->actionGet_ip_info($_SERVER[''REMOTE_ADDR]); 

// Немного строгой типизации ))

$city = (string) $ip_info->city;

//Можно запомнить название города, сохранив переменную в текущую сессию

Yii::app()->session['city'] = $city; 
yan
Сообщения: 942
Зарегистрирован: 2011.03.23, 09:28
Откуда: Уфа

Re: Определение Города по IP адресу

Сообщение yan »

только конечно такие вещи лучше не в контроллере делать и еще неплохо бы как-то кэшировать, как минимум из уважение к бесплатному сервису
p0rsche
Сообщения: 192
Зарегистрирован: 2012.01.18, 08:28
Контактная информация:

Re: Определение Города по IP адресу

Сообщение p0rsche »

а еще лучше использовать модули для веб-сервера.
valkiriy
Сообщения: 58
Зарегистрирован: 2010.05.25, 08:32

Re: Определение Города по IP адресу

Сообщение valkiriy »

еще как вариант использовать http://sypexgeo.net/ru/
pogranecua
Сообщения: 9
Зарегистрирован: 2013.05.07, 12:57

Re: Определение Города по IP адресу

Сообщение pogranecua »

Пользуюсь таким методом....
возвращает массив с ключами

Код: Выделить всё

public function getCountryCityFromIP()
{
//function to find country and city from IP address
    $ipAddr=CHttpRequest::getUserHostAddress();
//verify the IP address for the
ip2long($ipAddr)== -1 || ip2long($ipAddr) === false ? trigger_error("Invalid IP", E_USER_ERROR) : "";
$ipDetail=array(); //initialize a blank array

//get the XML result from hostip.info
$xml = file_get_contents("http://api.hostip.info/?ip=".$ipAddr);

//get the city name inside the node <gml:name> and </gml:name>
preg_match("@<Hostip>(.*?)<gml:name>(.*?)</gml:name>@si",$xml,$match);

    //assing the city name to the array
    $ipDetail['city']=$match[2];

    //get the country name inside the node <countryName> and </countryName>
    preg_match("@<countryName>(.*?)</countryName>@si",$xml,$matches);

    //assign the country name to the $ipDetail array
    $ipDetail['country']=$matches[1];

    //get the country name inside the node <countryName> and </countryName>
    preg_match("@<countryAbbrev>(.*?)</countryAbbrev>@si",$xml,$cc_match);
    $ipDetail['country_code']=$cc_match[1]; //assing the country code to array

    //return the array containing city, country and country code
    return $ipDetail;

    }


 
Дай глазам отдохнуть
http://releyes.com
Аватара пользователя
dignityinside
Сообщения: 76
Зарегистрирован: 2013.04.04, 17:57
Контактная информация:

Re: Определение Города по IP адресу

Сообщение dignityinside »

pogranecua писал(а):Пользуюсь таким методом....
возвращает массив с ключами

Код: Выделить всё

public function getCountryCityFromIP()
{
//function to find country and city from IP address
    $ipAddr=CHttpRequest::getUserHostAddress();
//verify the IP address for the
ip2long($ipAddr)== -1 || ip2long($ipAddr) === false ? trigger_error("Invalid IP", E_USER_ERROR) : "";
$ipDetail=array(); //initialize a blank array

//get the XML result from hostip.info
$xml = file_get_contents("http://api.hostip.info/?ip=".$ipAddr);

//get the city name inside the node <gml:name> and </gml:name>
preg_match("@<Hostip>(.*?)<gml:name>(.*?)</gml:name>@si",$xml,$match);

    //assing the city name to the array
    $ipDetail['city']=$match[2];

    //get the country name inside the node <countryName> and </countryName>
    preg_match("@<countryName>(.*?)</countryName>@si",$xml,$matches);

    //assign the country name to the $ipDetail array
    $ipDetail['country']=$matches[1];

    //get the country name inside the node <countryName> and </countryName>
    preg_match("@<countryAbbrev>(.*?)</countryAbbrev>@si",$xml,$cc_match);
    $ipDetail['country_code']=$cc_match[1]; //assing the country code to array

    //return the array containing city, country and country code
    return $ipDetail;

    }


Можно пример как использовать?
Мой блог:
https://protonalex.com
Nafania
Сообщения: 1227
Зарегистрирован: 2011.01.31, 13:12

Re: Определение Города по IP адресу

Сообщение Nafania »

Я просто оставлю это здесь http://www.yiiframework.com/extension/egeocoder/
Аватара пользователя
SiZE
Сообщения: 2817
Зарегистрирован: 2011.09.21, 12:39
Откуда: Perm
Контактная информация:

Re: Определение Города по IP адресу

Сообщение SiZE »

cezar, поправь $_SERVER[''REMOTE_ADDR]
Ответить