Setting a Country Cookie
When you know the site user's country, you can publish country-specific content.
Why would you want to do that? Here are a few examples to stimulate your imagination and creative process:
-
Publish a "Hello there, glad you could make it, all the way from [country]! I hope you find what you came for" greeting.
-
Present different ads or product descriptions for certain countries.
-
Populate a hidden field in your contact form so you know the country they're from when they submit the form.
-
Redirect the browser to a country-specific web page.
The PHP script further below checks to see if the country cookie is already set. If yes, it doesn't do anything else. Otherwise, the script:
-
Gets the user's IP address.
-
Gets the country from the IP address.
The country information is obtained from Geobytes.com. They provide up to 16,384 free lookups per hour (which comes to around 4.5 lookups per second or 393,216 lookups per day). If you need more than that, additional lookups can be purchased.
-
Stores the country name or abbreviation in the country cookie.
The PHP script has two customizations, which may be left as they are or updated according to your preference: (i) specifying the cookie name and (ii) specifying whether or not you want the full country name (if not, it gets the country's internet abbreviation).
If you make no changes, the cookie name is set up as "CountryFromIP" and it gets the country's internet abbreviation. See 2-Letter Country Name Abbreviations for a list. (Note: Although "GB" is the standard internet abbreviation for United Kingdom of Great Britain and Northern Ireland, the internet abbreviation "UK" is used by today's PHP script. It's a common exception.)
When the customization is done, the PHP script can be inserted into your web pages or included in your pages from an external file.
Here's the PHP script. Notes follow.
<?php /* Country Name From IP Address Cookie Setter Version 1.0 May 14, 2016 Will Bontrager Software LLC https://www.willmaster.com/ This software does a lookup at http://geobytes.com/get-city-details-api/ using code provided by Geobytes.com. As of May 14, 2016, their web page at http://geobytes.com/iplocator/ stated, "Gone is the 20 free lookups limit - you now get 16,384 free lookups per hour via our new Get City Details API (that is 4.5 lookups per second), and if that is not enough you can still purchase additional lookups, but at 1/10th of the price. (Reduced from 1/10th of a cent to 1/100th of cent.)" See also http://geobytes.com/geobytes-apis/ for a table of free limits. */ // Customization: // Specify a cookie name. $CookieName = "CountryFromIP"; // Letters a-z and A-Z and underscore characters only between the quotes. // Specify whether or not to read the full country name. (If not, only the country abbreviation will be read.) $ReadFullCountryName = false; // Use the digit 1 or the word true (no quotes) to read the full country name. Otherwise, use 0 or the word false (no quotes). // End of customization. if( empty($_COOKIE[$CookieName]) ) { GetIPaddressAndSetTheCookie($CookieName,$ReadFullCountryName); } function GetIPaddressAndSetTheCookie($cookieName,$fullName) { $which = ( $fullName or substr(strtoupper($fullName),0,1)=='T' or substr(strtoupper($fullName),0,1)=='Y' ) ? 'geobytescountry' : 'geobytesinternet'; $json = file_get_contents('http://getcitydetails.geobytes.com/GetCityDetails?fqcn='.GetIPaddress()); $data = json_decode($json,true); $country = $data[$which]; $_COOKIE[$cookieName] = $country; if( ! headers_sent() ) { setcookie($cookieName,$country,0,'/'); } echo("<script>document.cookie='$cookieName=$country; path=/'</script>"); } # function GetIPaddressAndSetTheCookie() function GetIPaddress() { foreach( array('HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_X_CLUSTER_CLIENT_IP', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'REMOTE_ADDR') as $key ) { if( array_key_exists($key, $_SERVER) === true ) { foreach( explode(',', $_SERVER[$key]) as $ip ) { if( filter_var($ip, FILTER_VALIDATE_IP) !== false ) { return $ip; } } } } } # function GetIPaddress() ?>
Notes:
There are two variables in the customization that may be customized. Both are colored blue and both are commented with pertinent information.
-
$CookieName = "CountryFromIP"; — As downloaded, the cookie name is "CountryFromIP". It may be changed.
-
$ReadFullCountryName = false; — As downloaded the full country name is specified as false so you'll get the internet abbreviation for the country. If you prefer to have the full country name, change the value to true (no quotes for true or false).
Installing the PHP Script
When the customization is done, the script can be installed by inserting it at the top of your current web pages. Or, if you have several or many pages, upload the script to your server and use the PHP include() function to pull it in.
How to use the include() function:
First, upload the PHP script into the same directory where your website's home or index page is at. Name the PHP script IP2country.php (or some other .php file name that makes sense to you). The examples assume a IP2country.php file name.
Then, at the top of every page, put this:
<?php include("{$_SERVER['DOCUMENT_ROOT']}/IP2country.php"); ?>
You're now good to go. The script will set a cookie with the country name (or abbreviation) for every browser that doesn't already have the cookie.
Using the Cookie Information
The country cookie can be consulted with either PHP or with JavaScript. There is one example of each.
The country of India will be used for every example that specifies a specific country.
For these examples of use, I'll make two assumptions: (1) The cookie name is "CountryFromIP" and (2) the country name is an abbreviation.
Using the country cookie with PHP:
Let's suppose you have specific content you want to publish only for visitors from India. The country name abbreviation for India is "IN".
Put the content to publish only for India between two PHP lines of code. Like this:
<?php if( isset($_COOKIE['CountryFromIP']) and $_COOKIE['CountryFromIP']=="IN" ): ?> [Content exclusively for visitors from India] <?php endif; ?>
That content will publish only if the IP address confirms the site user is connected to the internet from a location in India.
Another example: To populate a hidden field in a form with the country information, this will work (change a_field_name to a form field name expected by your form handling software).
<input
type="hidden"
name="a_field_name"
value="<?php echo(@$_COOKIE['CountryFromIP']) ?>">
That inserts the country information into the field as the field's value.
One more example: This will redirect the browser to a different web page if the country is India.
<?php if( isset($_COOKIE['CountryFromIP']) and $_COOKIE['CountryFromIP']=="IN" ) { header('Location: http://example.com/page-for-india.php'); exit; } ?>
The above code must be in the web page at the very top of the source code. No white space or characters may occur before that PHP code. Otherwise, the header() function won't work.
The header() function in the above code redirects the browser if the country is India.
Using the country cookie with JavaScript:
As before, let's suppose you have specific content to publish only for vistors from India.
Put the content into a div
with a CSS display:none;
declaration. Following that, JavaScript will change the display to block
if the visitor is from India.
<div id="unique-id-value" style="display:none;"> [Content exclusively for visitors from India] </div> <script> var country = ReadCookie("CountryFromIP"); if( country == "IN" ) { document.getElementById("unique-id-value").style.display = "block"; } function ReadCookie(n) { var cookiecontent = new String(); if(document.cookie.length > 0) { var cookiename = n+ '='; var cookiebegin = document.cookie.indexOf(cookiename); var cookieend = 0; if(cookiebegin > -1) { cookiebegin += cookiename.length; cookieend = document.cookie.indexOf(";",cookiebegin); if(cookieend < cookiebegin) { cookieend = document.cookie.length; } cookiecontent = document.cookie.substring(cookiebegin,cookieend); } } return unescape(cookiecontent); } // function ReadCookie() </script>
The id value of the div with the India content and the id value specified in the JavaScript need to be identical. They're colored blue in the above source code.
Another example: To populate a hidden field in a form with the country information, this will work (change a_field_name to a form field name expected by your form handling software).
<script>
document.write('<input type="hidden" name="a_field_name" value="' + ReadCookie("CountryFromIP") + '">');
function ReadCookie(n)
{
var cookiecontent = new String();
if(document.cookie.length > 0)
{
var cookiename = n+ '=';
var cookiebegin = document.cookie.indexOf(cookiename);
var cookieend = 0;
if(cookiebegin > -1)
{
cookiebegin += cookiename.length;
cookieend = document.cookie.indexOf(";",cookiebegin);
if(cookieend < cookiebegin) { cookieend = document.cookie.length; }
cookiecontent = document.cookie.substring(cookiebegin,cookieend);
}
}
return unescape(cookiecontent);
} // function ReadCookie()
</script>
That inserts the country information into the field as the field's value.
One more example: This will redirect the browser to a different web page if the country is India.
<script> var country = ReadCookie("CountryFromIP"); if( country == "IN" ) { location = "http://example.com/page-for-india.php"; } function ReadCookie(n) { var cookiecontent = new String(); if(document.cookie.length > 0) { var cookiename = n+ '='; var cookiebegin = document.cookie.indexOf(cookiename); var cookieend = 0; if(cookiebegin > -1) { cookiebegin += cookiename.length; cookieend = document.cookie.indexOf(";",cookiebegin); if(cookieend < cookiebegin) { cookieend = document.cookie.length; } cookiecontent = document.cookie.substring(cookiebegin,cookieend); } } return unescape(cookiecontent); } // function ReadCookie() </script>
The above code redirects the browser if the country is India.
PHP and JavaScript differences:
With PHP, the India content can't be seen in the web page source code when the visitor is from a country other than India. With JavaScript, the content can be seen in the source code even though it isn't published on the page.
For any method to publish country-specific content on your web pages, the country must be known. The PHP script to obtain the country by the site visitor's IP address is one way to get that information.
(This article first appeared in Possibilities ezine.)
Will Bontrager