Display Visitor’s Country Currency Using PHP and BIN Database

In this tutorial, we demonstrate you on how to display visitor’s country currency based on their IP address using PHP programming languages and IP2Location BIN database. This tutorial uses the IP2Location module to query IP information from BIN database and free BIN databases are available for download at IP2Location LITE database.

Step 1: Download IP2Location LITE database, unzip the file and copy the BIN database (.bin extension) into the same directory of where you save your sample code.

Step 2: Download IP2Location PHP class module, unzip the file and copy IP2Location.php into the same directory of where you save your sample code.

Step 3: Run the below sample code.

<?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 \IP2Location\Database('./databases/IP2LOCATION-LITE-DB1.BIN', \IP2Location\Database::FILE_IO);
 
    $ip = $_SERVER['REMOTE_ADDR'];
 
    //lookup for country code
    $country_code = $loc->lookup($ip, \IP2Location\Database::COUNTRY_CODE);
 
    //Lookup and display country code and country name
    echo "Country Code: " . $loc->lookup($ip, \IP2Location\Database::COUNTRY_CODE) . "<br />";
    echo "Country Name: " . $loc->lookup($ip, \IP2Location\Database::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;
    }
?>

Was this article helpful?

Related Articles