Get country IP address in php

→ Are you a new visitor? Please visit the page guidance for new visitors ←

Get country IP address in php

I was checking around stackoverflow recently and I tend to look at what people are doing or making and getting what I know refreshed or trying to learn new tricks from here and there. Today I saw one user trying to get country IP address in php and I was “hey, there’s an easy way without relying on that GeoIPService”. And that is indeed true, if you’ve read my other articles, you would see I’ve played alot with CDN networks, well one of them, Cloudflare to be exact, has the option to help us directly by providing the country IP Code. And I’m going to show you this how it is done in this article.

Activate cloudflare on your domain

First you will need to activate cloudflare on your domain name, this can be done easily on your hosting provider (now days almost everyone have this option) or adding your domain directly on their website after you signup:

You then want to enable the option to pass the header information that contains the country (GeoIP) of the IP address.

This is done in section Cloudflare Settings specific to your domain name.

Get Country IP address - geolocation Cloudflare

Country IP geolocation Cloudflare

On the same page you also have a nice little example there how you can get the country code for each IP address passing through Cloudlare, so you just use the code:

The result would look similar to:

An example can be found here:

Using Soap client to get country IP

In the same way, but using php SoapClient to get the information from Personally I don’t really like it this way, but it is a nice and easy way using other public services that already offers these data for you to use.

You can use the bellow code for getting the country code:

An example can be seen here (without www):

I’m pretty sure there are other ways to get the country IP address, but these ones are as simple as it gets, especially the Cloudflare one which you just need to read the http header that cloudflare are kind enough to send.

Comment bellow if you know any other quick and simple methods to get this information and don’t forget to subscribe!

Request an article ←