28Jul

Get the city name from a user’s IP address in PHP (free up to 50K requests per month)

In a WordPress blog, I wanted to display different content to users depending on their location. It is possible using IPInfo.io (for free until 50k requests a month, then you can get a paid plan). Here is how to get the city name or country name from an IP.

WordPress: get city name from IP without plugin

You might have looked at some Geolocation Plugins (i.e.: https://en-gb.wordpress.org/plugins/geoip-detect/) to display the city name based on the IP Address of a visitor. But there is no need for an extra plugin… the less plugin the better.

How to get the user’s city or country name in PHP

This is not for WordPress only, can be any PHP-based CMS (Drupal, Craft CMS, Joomla, etc) or just a PHP page

You first need to register at https://ipinfo.io/

Select the “Free plan – Geolocation: 50k requests per month” and get your unique token.

Then go to your PHP template and use a code similar to the below:

<?php
$ip = $_SERVER['REMOTE_ADDR']; // get the user IP (if not using a VPN...) 
$details = json_decode(file_get_contents("http://ipinfo.io/{$ip}/json?token=xxxxxxxxxxxxxx"));
if($details->city == "London") {    
    ?>
    London targeted content
    <?php
}
else {
    if($details->country == "GB") {
        ?>
        UK content
        <?php
    }
    else {
        ?>
        Outside UK content
        <?php
    }
}

That’s all!

The documentation at https://ipinfo.io/developers is really well explained. You can get the user’s city from his IP address in JavaScript too if that is what you need. Just look at the JSONP/ CORS Requests example in the documentation.

You get a 7 days premium if you need deeper functionalities.

Please note if your website/app visitors are using a VPN to hide their IP then this won’t work as expected as you won’t have their real IP location.

Hope this can help! Happy days

Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments