Get country IP address in php
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:
https://www.cloudflare.com/sign-up
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.
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:
1 2 3 4 |
<?php $country_code = $_SERVER["HTTP_CF_IPCOUNTRY"]; echo "Country code is " . $country_code; ?> |
The result would look similar to:
1 |
Country code is UK |
An example can be found here:
http://www.ajutorpe.net/scripts/cloudflare-country-ip-example.php
Using Soap client to get country IP
In the same way, but using php SoapClient to get the information from webservicex.net. 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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<?php echo "########################################<br/>"; $client = new SoapClient("http://www.webservicex.net/geoipservice.asmx?WSDL"); $params = new stdClass; $params->IPAddress = $_SERVER['REMOTE_ADDR']; echo "Client IP address: " .$params->IPAddress; $result = $client->GetGeoIP($params); // Check for errors... $countryName = $result->GetGeoIPResult->CountryName; $countryCode = $result->GetGeoIPResult->CountryCode; echo "<br/>Country name is: " . $countryName . "<br/>Country code is " . $countryCode; echo "<br/>########################################<br/>"; ?> |
An example can be seen here (without www):
http://ajutorpe.net/scripts/soap-client-country-ip.php
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!