[Drupal 6] How to get the IP address and Country code using the API key of a third party service?
If you need to deliver a custom tailored home page to a user visiting your Drupal website based on their actual physical location you need to need to match their ip addresses with their actual physical location. There are many third party services that provide this functionality and you need to use the API key provided by them in your Drupal application. If you need to know how to get IP address and Country code from an API key to be used in your Drupal application then read on to know more.
One of our Drupal clients had requested us to redirect users coming to their Drupal site to a country specific page in the website tailored for that location. If the country code was IN the user needed to be redirected to the home page designed for Indian users of their website and UK users were subsequently redirected to a page designed to meet the needs of UK residents. To meet the needs of the client we used the API of a third party service IpinfoDB which provided us with their API Key.
Steps
Follow the steps below to use the API of IpinfoDB in your Drupal in
- Download ip2locationlite.zip, and unzip it into the folder of your custom module
- Write a function to get your IP address and store it in a variable.
- Using the above IP address you can get the country code.
- Now lets have a look at the function to get the IP address:
function _mymodule_get_ip(){ $ip = $_SERVER['REMOTE_ADDR']; return $ip; }
- Here is the function to get the country code
function _mymodule_get_cc($user_ip){ // Set mymodule_geolocation cookie include_once('ip2locationlite/ip2locationlite.class.php'); if (!$_COOKIE["mymodule_location"]) { $ipLite = new ip2location_lite; $ipLite->setKey('your_api_key'); $visitorGeolocation = $ipLite->getCountry($user_ip); if ($visitorGeolocation['statusCode'] == 'OK') { $cc = $visitorGeolocation['countryCode']; setcookie("mymodule_location", $cc, time()+3600*24*7); } else { $cc =''; } } else { $cc = $_COOKIE["mymodule_location"]; }
The above code does the following:
- The function _mymodule_get_ip() returns the IP address and stores it in the variable $ip.
- The IP address is passed to the function _mymodule_get_cc() to get our country code.
- In the function _mymodule_get_cc() we initially include ip2locationlite.class.php and the function checks whether the cookie mymodule_location has been set
- If its not set, we set our API key to the variable $ipLite and thus we get the country code in the variable $cc.
Hope the article was helpful. Please use the comment form below to shoot your questions.
References:
1. http://ipinfodb.com/ip_location_api.php