I already search on google how to get city name by ip address for few hours, and found a simple way using third party REST API. There are many services which can provide the data for free. In this tutorial we get the data from keycdn and ipapi
PHP Code
<?php if (!empty($_SERVER['HTTP_CLIENT_IP'])) { $ip = $_SERVER['HTTP_CLIENT_IP']; } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) { $ip = $_SERVER['HTTP_X_FORWARDED_FOR']; } else { $ip = $_SERVER['REMOTE_ADDR']; } // get city name from keycdn geo json $json = "https://tools.keycdn.com/geo.json?host=$ip"; $data = file_get_contents($json); $data = json_decode($data, true); $kota = $data['data']['geo']['city']; // get city name from ipapi json $url = "https://ipapi.co/json/"; $data = file_get_contents($json); $kota = $data['city']; // Show it echo $kota; ?>
There are limitation for each free service. But i think it’s good enough to use it for development purpose.