PHP

GET USER'S LOCATION FROM IP ADDRESS

(a quick example)

SOME QUICK NOTES

01

- Each region has their own specific range of IP address.

- A reverse check on the IP address will give the user's approximate location.

- This is called IP Geolocation.

- PHP does not maintain list of IP Geolocations. We need to use online services.

SIGN UP FREE IP GEOLOCATE

02

- Get the API endpoint address and also the API key.

PHP USER IP GEOLOCATION (A)

03

API SETTINGS $settings = [   "apiKey" => "YOUR-API-KEY",   "ip" => $_SERVER['REMOTE_ADDR'],   "lang" => "en", "fields" => "*" ];

SERVICE URL $url = "https://api.ipgeolocation.io/ipgeo?"; foreach ($settings as $k=>$v) {   $url .= urlencode($k) . "="             . urlencode($v) . "&";  } $url = substr($url, 0, -1);

PHP USER IP GEOLOCATION (B)

04

INIT CURL $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

PHP USER IP GEOLOCATION (C)

05

CURL FETCH $result = curl_exec($ch); if (curl_errno($ch)) { echo curl_error($ch); } else {   $info = curl_getinfo($ch);   $result = json_decode($result, 1);   print_r($result);  } curl_close($ch);