GeoIP Tutorial: Implementation
In this part of the SiteGround's GeoIP tutorial we will give an example how to use the GeoIP API in your web site.
Lets imagine that you have a custom developed php web site and you want to get the visitors' location using the GeoIP API.
First, you should get the geoip.inc and the GeoLite Country Binary Format files. Extract the archive of the last file on your local computer and upload them in your web site's root folder.
Then open the file where you want to include the GeoIP code. Usually such a file will be called every time the index.php file is loaded. Or you can insert the code directly in the index.php file.
Check the following sample code:
require($website_root_path . 'geoip.inc');
$gi=geoip_open($website_root_path . 'GeoIP.dat',GEOIP_STANDARD);
echo geoip_country_code_by_addr($gi, $ip) . " ";
echo geoip_country_name_by_addr($gi, $ip);
In the first line we set a new variable. Its value is the absolute path to the web site's root folder.
Then we include the geoip.inc file. Next, the ip variable gets the web site visitor's IP.
After that the GeoIP database is opened.
The visitor's IP address is compared against the IP ranges included in the database through the corresponding functions. As a result the visitor's country code and the country name are visualized. At the end the access to the database file is closed.
You can put the above code excerpt in your web site's code and get the country location of your web site visitors. Then you can use the results for your own purposes.