Geolocation.class.php 2.05 KB
<?php

namespace SH;

class Geolocation
{
    static $names = array(
        'country' => 'Страна',
        'district' => 'Округ',
        'region' => 'Регион',
        'city' => 'Город',
        'ip' => 'IP-адрес'
    );

    static function toString()
    {
		$data = self::getData();

        $data['ip'] = $_SERVER['REMOTE_ADDR'];

        $result = '';

        foreach($data as $key => $val) {
            if($val) {
                if($result) {
                    $result .= "\n";
                }
                $result .= (isset(self::$names[$key]) ? self::$names[$key] : $key) . ': ' . $val;
            }
        }

        return $result;
    }

    static function getData()
    {
        static $data;

        if (!isset($data)) {

//            if (!empty($_SESSION['geolocation-data'])) {
//                $data = json_decode($_SESSION['geolocation-data'], true);
//                if (!is_array($data) || !isset($data['city'])) $data = false;
//            }

            if (!$data) {
                $data = array();

                try {
					//$geolocator = new \Cpeople\Classes\Geolocation\LocatorIpgeobase();

					//if ($_SERVER['REMOTE_ADDR'] == '127.0.0.1') {
					//$geolocator->setIP('109.110.70.1');
//                        $geolocator->setIP('127.0.0.1');
					//}

					//$result = $geolocator->locate();

					//if ($result->isError()) throw new \Exception();

					//$data['country'] = $result->getCountry();
					//$data['district'] = $result->getDestrict();
					//$data['region'] = $result->getRegion();
					//$data['city'] = $result->getCity();

                   $data1=geoip_record_by_name($_SERVER['REMOTE_ADDR']);
				   $data['country'] = $data1["country_name"];
				   $data['district'] = '';//$result->getDestrict();
				   $data['region'] = geoip_region_name_by_code($data1["country_code"],$data1["region"]);
				   $data['city'] = $data1["city"];

                } catch (\Exception $e) {
                }

                $_SESSION['geolocation-data'] = $data;
            }
        }

        return $data;
    }
}