Aman
Aman

Reputation: 137

getCity/state from IP address using PHP

I am working on a client project, where he needs the city/state of the user by taking his ip address.

1) he has purchased maxmind GeoIP2 Precision, but no idea how to implement the code in php. documentation says some instruction to download composer.exe, when i downloaded it, it is asking me to download php.exe then after download php.exe, i tried to install composer.exe then it tried to install composer.phar and gave me this error

"Some settings on your machine make Composer unable to work properly. Make sure that you fix the issues listed below and run this script again:

The openssl extension is missing, which means that secure HTTPS transfers are impossible. If possible you should enable it or recompile php with --with-openssl "

Please suggest me the easiest way to get the city/state from IP address using PHP.

Thanks

Upvotes: 4

Views: 20115

Answers (4)

ooi18
ooi18

Reputation: 142

It's easier to use any API service to get the city and state information for an IP address. For example, to get the city name and state name for an IP address using IP2Location.io,

<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.ip2location.io/?' . http_build_query([
    'ip'      => '8.8.8.8',
    'key'     => 'YOUR_API_KEY',
    'format'  => 'json',
    'lang'    => 'en',
]));
curl_setopt($ch, CURLOPT_FAILONERROR, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
$response = curl_exec($ch);
$response_array = json_decode($response, true);
echo 'City Name: ' . $response_array["city_name"];
echo 'State Name: ' . $response_array["region_name"];

Upvotes: 0

user10398534
user10398534

Reputation: 165

No need to pay for an API or be bound by ridiculous rate limits. https://www.php.net/manual/en/book.geoip.php

Upvotes: 3

Hamza Zafeer
Hamza Zafeer

Reputation: 2436

JSON can also be used, because Serialized PHP endpoint is deprecated.

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;

Upvotes: 5

Adam Joseph Looze
Adam Joseph Looze

Reputation: 1021

This API will get your location details. Try this

    <?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'];
    }
    ?>

Here are the outputs you can use. Call them using the key;

    <?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',
    );
    ?>

This will not be reliable for mobile. If you are on mobile, you can use the following 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>

This will use the gps built in to the device and get the cordinates. Then you can cross reference with a database filled with cords. (thats one option, and thats what i do).

You can find a city lat lng databases online if you search and if thats what you chose to do for mobile.

Upvotes: 19

Related Questions