|Where are you from? IP Geolocation|
|Written by Harry Fairhead|
|Wednesday, 15 February 2012|
Page 2 of 2
Finding the user's IP address
The next problem is to find the user's IP address. This is more difficult than you might think because a proxy might be in use. The standard solution is:
Now we have the IP address we can start the lookup process but first we need to create a GeoIP object:
and use it to lookup the IP and return a country code:
You could now set the cookie using the country code but as this particular application needs region codes which aggregate multiple countries we have to recode (only part of the switch statement is listed to give you the idea):
Finally we set a new cookie with a one-year expiry date associated with the entire site, i.e. from the root directory down:
That’s all there is to it and to build it into the Joomla site all that has to be done is to include the findRegion.php file in a suitable PHP code file that is loaded with every page.
You could add it to the master index.php which is stored in the root. This is where every page in a Joomla site starts off from but this would be modifying the Joomla framework and isn't a good idea if you can avoid it.
Much better is to place it in index.php stored in the template you are currently using. So, for example, if you were using the standard rhuk_milkyway template you would add the line:
i.e. start of the file would read:
Finally we have to ask the obvious but often overlooked question.
Does it work?
Testing locally isn't useful because at most that provides a single IP to check and in many cases it will be a non-public IP which doesn't have a country associated with it. The only reasonable solution is to add some code for logging. If you add, within the else part of if statement:
$File = "Geo.csv";
then the PHP code will write a CSV file in the Geolite directory containing time, IP, region and country code. It's easy enough to change the location of the log file.
Make sure you remove the code or add a flag to switch it off otherwise the file could get very big over the course of a few months.
or email your comment to: email@example.com
|Last Updated ( Friday, 17 February 2012 )|