Where are you from? IP Geolocation |
Written by Harry Fairhead | ||||||
Wednesday, 15 February 2012 | ||||||
Page 2 of 2
Finding the user's IP addressThe 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: if ($_SERVER['HTTP_X_FORWARD_FOR']) 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: $ccode= geoip_country_code_by_addr( 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): switch ($ccode){ Finally we set a new cookie with a one-year expiry date associated with the entire site, i.e. from the root directory down: setcookie('Region', 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: include(JPATH_BASE .DS.'includes'.DS. to \templates\rhuk_milkyway\index.php i.e. start of the file would read: <?php 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. If you would like the source code of this project register with I Programmer and visit the CodeBin.
Comments
or email your comment to: comments@i-programmer.info
To be informed about new articles on I Programmer, subscribe to the RSS feed, follow us on Google+, Twitter, Linkedin or Facebook or sign up for our weekly newsletter.
<ASIN:0672329166> <ASIN:1449308449> <ASIN:0596006306> <ASIN:1430228024> <ASIN:1593272715> |
||||||
Last Updated ( Friday, 17 February 2012 ) |