Dynamically displaying a visitor’s local currency based on their location significantly enhances the user experience, especially for e-commerce and SaaS platforms.
This tutorial demonstrates how to retrieve and display a visitor’s country currency from their IP address using PHP and the IP2Location BIN database. This method uses a local .bin file, which allows for ultra-fast, offline lookups without relying on third-party API calls.
Prerequisites & Setup #
Step 1: Download the IP2Location BIN Database #
- Download the free IP2Location LITE database (or the commercial version) from the IP2Location LITE Download Page.
- Unzip the downloaded file and copy the binary file into your project’s root directory.
Step 2: Download the IP2Location PHP Module #
- Download the official IP2Location PHP Module.
- If downloading manually, extract the package and copy the
IP2Location.phpfile into your project’s root directory.
Step 3: Implementation #
Create a new file in the same folder and add the following sample code:
PHP
<?php
// Preset PHP settings
error_reporting(E_ALL);
ini_set('display_errors', 1);
set_time_limit(0);
require_once('IP2Location.php');
// Standard lookup with no cache
$loc = new IP2LocationDatabase('./databases/IP2LOCATION-LITE-DB1.BIN', IP2LocationDatabase::FILE_IO);
$ip = $_SERVER['REMOTE_ADDR'];
//lookup for country code
$country_code = $loc->lookup($ip, IP2LocationDatabase::COUNTRY_CODE);
//Lookup and display country code and country name
echo "Country Code: " . $loc->lookup($ip, IP2LocationDatabase::COUNTRY_CODE) . "<br />";
echo "Country Name: " . $loc->lookup($ip, IP2LocationDatabase::COUNTRY_NAME) . "<br />";
//Displaying currency code based on country code retrieved.
//If no record of currency code or no country code is found, default will be used.
switch($country_code)
{
case 'CA':
$currency_code = "CAD";
echo "Country Currency: $currency_code 100";
break;
case 'MY':
$currency_code = "MYR";
echo "Country Currency: $currency_code 100";
break;
case 'JP':
$currency_code = "JPY";
echo "Country Currency: $currency_code 100";
break;
case 'US':
$currency_code = "USD";
echo "Country Currency: $currency_code 100";
break;
default:
echo "Unable to translate IP to country. <br />";
echo "$100.00";
break;
}
?>
