getCity/state 来自 IP 地址使用 PHP

getCity/state from IP address using PHP

我正在做一个客户项目,他需要通过获取用户的 IP 地址来 city/state。

1) 他购买了 maxmind GeoIP2 Precision,但不知道如何实现 php 中的代码。文档说了一些下载 composer.exe 的说明,当我下载它时,它要求我下载 php.exe 然后在下载 php.exe 之后,我尝试安装 composer.exe 然后它尝试安装 composer.phar 并给了我这个错误

“您机器上的某些设置使 Composer 无法正常工作。请确保您修复了下面列出的问题并再次 运行 此脚本:

缺少 openssl 扩展,这意味着无法进行安全的 HTTPS 传输。如果可能,您应该启用它或使用 --with-openssl "

重新编译 php

请建议我使用 PHP 从 IP 地址获取 city/state 的最简单方法。

谢谢

此 API 将获取您的位置详细信息。试试这个

    <?php
    $ip = '168.192.0.1'; // your ip address here
    $query = @unserialize(file_get_contents('http://ip-api.com/php/'.$ip));
    if($query && $query['status'] == 'success')
    {
        echo 'Your City is ' . $query['city'];
        echo '<br />';
        echo 'Your State is ' . $query['region'];
        echo '<br />';
        echo 'Your Zipcode is ' . $query['zip'];
        echo '<br />';
        echo 'Your Coordinates are ' . $query['lat'] . ', ' . $query['lon'];
    }
    ?>

这是您可以使用的输出。使用按键呼叫他们;

    <?php
    array (
      'status' => 'success',
      'country' => 'COUNTRY',
      'countryCode' => 'COUNTRY CODE',
      'region' => 'REGION CODE',
      'regionName' => 'REGION NAME',
      'city' => 'CITY',
      'zip' => 'ZIP CODE',
      'lat' => 'LATITUDE',
      'lon' => 'LONGITUDE',
      'timezone' => 'TIME ZONE',
      'isp' => 'ISP NAME',
      'org' => 'ORGANIZATION NAME',
      'as' => 'AS NUMBER / NAME',
      'query' => 'IP ADDRESS USED FOR QUERY',
    );
    ?>

这对移动设备来说不可靠。如果您使用的是移动设备,则可以使用以下 javascript

    <script>
    var x = document.getElementById("demo");
    function getLocation() {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(showPosition);
        } else {
            x.innerHTML = "Geolocation is not supported by this browser.";
        }
    }
    function showPosition(position) {
        x.innerHTML = "Latitude: " + position.coords.latitude + 
        "<br>Longitude: " + position.coords.longitude; 
    }
    </script>

这将使用设备内置的 gps 并获取坐标。然后,您可以与充满绳索的数据库进行交叉引用。 (这是一个选择,这就是我所做的)。

如果您搜索的话,您可以在线找到一个城市的经纬度数据库,如果那是您选择为移动设备做的。

JSON也可以使用,因为Serialized PHP endpoint已弃用。

Deprecated Use JSON. Almost all PHP sites now support json_decode(), and it's faster than unserialize()

function get_ip_detail($ip){
   $ip_response = file_get_contents('http://ip-api.com/json/'.$ip);
   $ip_array=json_decode($ip_response);
   return  $ip_array;
 }

 $user_ip=$_SERVER['REMOTE_ADDR'];
 $ip_array= get_ip_detail($user_ip);
 echo $country_name=$ip_array->country; 
 echo $city=$ip_array->city;

无需支付 API 费用或受荒谬的费率限制约束。 https://www.php.net/manual/en/book.geoip.php