Skip to content

How to Converter Currency Using PHP

  • by
Converter Currency Using PHP

Currency Converter is used to convert one currency into another currency. Previously for Converter Currency Using PHP, we are using Google Finance API. But now Google Finance API is deprecated and no longer supported by Google.

So it means no future development, and no bug fixes will be done in Google finance API. Also according to the latest update, Google Finance API is stopped functioning.

All the website that is using Google Finance API should be a switch to the alternative of Google Finance API.

In this post, we have used the alternative of Google Finance API and created a currency converter system using PHP

For creating the currency converter we are using currencyconverterapi.com API .
currencyconverterapi.com provides two types of API for the currency conversion.

First one is the free version it has some limitation like we can call API only certain times in hours, other is the premium version that has no limitations like API call limit in the hour, etc

Currencyconvertor.com API integration is very easy and simple and it returns the response in the JSON and JSONP Data format. We can easily handle response according to our requirements.

In this tutorial we are using the free version of the currencyconverterapi.com API, the free version has some limitations. We have listed down all the limitations below.

Some of The limitations of using the free version of currencyconverterapi.com API

  • Conversion Pairs per Request Is : 2
  • Number of Requests per Hour: 100
  • Date Range in History: 8 Days
  • Allowed Back in History: 1 Year(s)

For using the currencyconverterapi.com free version API follow below steps

  • Visit this link Free Currency Convertor API
  • Click on generate API key link
  • Enter email id and click on the Get Your Free API Key button
  • You will get the api key on email id
  • Save the API key securely,these api key is needed when we calling the API

Converter Currency Using PHP

So now we can move to the coding parts and create currency converter system using PHP:

File structure for the currency converter system is the following.

index.php :- Currency converter form
currency-converter.php :- PHP file that handles logic for the currency conversion
script.js :- JavaScript file Handle ajax request
db-connection.php :- This file contains database connection details

Step 1: Create currency_list table and insert some record in currency_list table

--
-- Table structure for table `currency_list`
--

CREATE TABLE `currency_list` (
  `id` int(11) NOT NULL,
  `currency_id` varchar(255) NOT NULL,
  `currency_name` varchar(255) NOT NULL,
  `currency_symbol` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `currency_list`
--

INSERT INTO `currency_list` (`id`, `currency_id`, `currency_name`, `currency_symbol`) VALUES
(1, 'ALL', 'Albanian Lek', 'Lek'),
(2, 'XCD', 'East Caribbean Dollar', '$'),
(3, 'EUR', 'Euro', '€'),
(4, 'BBD', 'Barbadian Dollar', '$'),
(5, 'BTN', 'Bhutanese Ngultrum', ''),
(6, 'BND', 'Brunei Dollar', '$'),
(7, 'XAF', 'Central African CFA Franc', ''),
(8, 'CUP', 'Cuban Peso', '$'),
(9, 'USD', 'United States Dollar', '$'),
(10, 'FKP', 'Falkland Islands Pound', '£'),
(11, 'GIP', 'Gibraltar Pound', '£'),
(12, 'HUF', 'Hungarian Forint', 'Ft'),
(13, 'IRR', 'Iranian Rial', 'ï·¼'),
(14, 'JMD', 'Jamaican Dollar', 'J$'),
(15, 'AUD', 'Australian Dollar', '$'),
(16, 'LAK', 'Lao Kip', 'â‚­'),
(17, 'LYD', 'Libyan Dinar', ''),
(18, 'MKD', 'Macedonian Denar', 'ден'),
(19, 'XOF', 'West African CFA Franc', ''),
(20, 'NZD', 'New Zealand Dollar', '$'),
(21, 'OMR', 'Omani Rial', 'ï·¼'),
(22, 'PGK', 'Papua New Guinean Kina', ''),
(23, 'RWF', 'Rwandan Franc', ''),
(24, 'WST', 'Samoan Tala', ''),
(25, 'RSD', 'Serbian Dinar', 'Дин.'),
(26, 'SEK', 'Swedish Krona', 'kr'),
(27, 'TZS', 'Tanzanian Shilling', 'TSh'),
(28, 'AMD', 'Armenian Dram', ''),
(29, 'BSD', 'Bahamian Dollar', '$'),
(30, 'BAM', 'Bosnia And Herzegovina Konvertibilna Marka', 'KM'),
(31, 'CVE', 'Cape Verdean Escudo', ''),
(32, 'CNY', 'Chinese Yuan', 'Â¥'),
(33, 'CRC', 'Costa Rican Colon', 'â‚¡'),
(34, 'CZK', 'Czech Koruna', 'Kč'),
(35, 'ERN', 'Eritrean Nakfa', ''),
(36, 'GEL', 'Georgian Lari', ''),
(37, 'HTG', 'Haitian Gourde', ''),
(38, 'INR', 'Indian Rupee', '₹'),
(39, 'JOD', 'Jordanian Dinar', ''),
(40, 'KRW', 'South Korean Won', 'â‚©'),
(41, 'LBP', 'Lebanese Lira', '£'),
(42, 'MWK', 'Malawian Kwacha', ''),
(43, 'MRO', 'Mauritanian Ouguiya', ''),
(44, 'MZN', 'Mozambican Metical', ''),
(45, 'ANG', 'Netherlands Antillean Gulden', 'Æ’'),
(46, 'PEN', 'Peruvian Nuevo Sol', 'S/.'),
(47, 'QAR', 'Qatari Riyal', 'ï·¼'),
(48, 'STD', 'Sao Tome And Principe Dobra', ''),
(49, 'SLL', 'Sierra Leonean Leone', ''),
(50, 'SOS', 'Somali Shilling', 'S'),
(51, 'SDG', 'Sudanese Pound', ''),
(52, 'SYP', 'Syrian Pound', '£'),
(53, 'AOA', 'Angolan Kwanza', ''),
(54, 'AWG', 'Aruban Florin', 'Æ’'),
(55, 'BHD', 'Bahraini Dinar', ''),
(56, 'BZD', 'Belize Dollar', 'BZ$'),
(57, 'BWP', 'Botswana Pula', 'P'),
(58, 'BIF', 'Burundi Franc', ''),
(59, 'KYD', 'Cayman Islands Dollar', '$'),
(60, 'COP', 'Colombian Peso', '$'),
(61, 'DKK', 'Danish Krone', 'kr'),
(62, 'GTQ', 'Guatemalan Quetzal', 'Q'),
(63, 'HNL', 'Honduran Lempira', 'L'),
(64, 'IDR', 'Indonesian Rupiah', 'Rp'),
(65, 'ILS', 'Israeli New Sheqel', '₪'),
(66, 'KZT', 'Kazakhstani Tenge', 'лв'),
(67, 'KWD', 'Kuwaiti Dinar', ''),
(68, 'LSL', 'Lesotho Loti', ''),
(69, 'MYR', 'Malaysian Ringgit', 'RM'),
(70, 'MUR', 'Mauritian Rupee', '₨'),
(71, 'MNT', 'Mongolian Tugrik', 'â‚®'),
(72, 'MMK', 'Myanma Kyat', ''),
(73, 'NGN', 'Nigerian Naira', '₦'),
(74, 'PAB', 'Panamanian Balboa', 'B/.'),
(75, 'PHP', 'Philippine Peso', '₱'),
(76, 'RON', 'Romanian Leu', 'lei'),
(77, 'SAR', 'Saudi Riyal', 'ï·¼'),
(78, 'SGD', 'Singapore Dollar', '$'),
(79, 'ZAR', 'South African Rand', 'R'),
(80, 'SRD', 'Surinamese Dollar', '$'),
(81, 'TWD', 'New Taiwan Dollar', 'NT$'),
(82, 'TOP', 'Paanga', ''),
(83, 'VEF', 'Venezuelan Bolivar', ''),
(84, 'DZD', 'Algerian Dinar', ''),
(85, 'ARS', 'Argentine Peso', '$'),
(86, 'AZN', 'Azerbaijani Manat', 'ман'),
(87, 'BYR', 'Belarusian Ruble', 'p.'),
(88, 'BOB', 'Bolivian Boliviano', '$b'),
(89, 'BGN', 'Bulgarian Lev', 'лв'),
(90, 'CAD', 'Canadian Dollar', '$'),
(91, 'CLP', 'Chilean Peso', '$'),
(92, 'CDF', 'Congolese Franc', ''),
(93, 'DOP', 'Dominican Peso', 'RD$'),
(94, 'FJD', 'Fijian Dollar', '$'),
(95, 'GMD', 'Gambian Dalasi', ''),
(96, 'GYD', 'Guyanese Dollar', '$'),
(97, 'ISK', 'Icelandic Króna', 'kr'),
(98, 'IQD', 'Iraqi Dinar', ''),
(99, 'JPY', 'Japanese Yen', 'Â¥'),
(100, 'KPW', 'North Korean Won', 'â‚©'),
(101, 'LVL', 'Latvian Lats', 'Ls'),
(102, 'CHF', 'Swiss Franc', 'Fr.'),
(103, 'MGA', 'Malagasy Ariary', ''),
(104, 'MDL', 'Moldovan Leu', ''),
(105, 'MAD', 'Moroccan Dirham', ''),
(106, 'NPR', 'Nepalese Rupee', '₨'),
(107, 'NIO', 'Nicaraguan Cordoba', 'C$'),
(108, 'PKR', 'Pakistani Rupee', '₨'),
(109, 'PYG', 'Paraguayan Guarani', 'Gs'),
(110, 'SHP', 'Saint Helena Pound', '£'),
(111, 'SCR', 'Seychellois Rupee', '₨'),
(112, 'SBD', 'Solomon Islands Dollar', '$'),
(113, 'LKR', 'Sri Lankan Rupee', '₨'),
(114, 'THB', 'Thai Baht', '฿'),
(115, 'TRY', 'Turkish New Lira', ''),
(116, 'AED', 'UAE Dirham', ''),
(117, 'VUV', 'Vanuatu Vatu', ''),
(118, 'YER', 'Yemeni Rial', 'ï·¼'),
(119, 'AFN', 'Afghan Afghani', 'Ø‹'),
(120, 'BDT', 'Bangladeshi Taka', ''),
(121, 'BRL', 'Brazilian Real', 'R$'),
(122, 'KHR', 'Cambodian Riel', '៛'),
(123, 'KMF', 'Comorian Franc', ''),
(124, 'HRK', 'Croatian Kuna', 'kn'),
(125, 'DJF', 'Djiboutian Franc', ''),
(126, 'EGP', 'Egyptian Pound', '£'),
(127, 'ETB', 'Ethiopian Birr', ''),
(128, 'XPF', 'CFP Franc', ''),
(129, 'GHS', 'Ghanaian Cedi', ''),
(130, 'GNF', 'Guinean Franc', ''),
(131, 'HKD', 'Hong Kong Dollar', '$'),
(132, 'XDR', 'Special Drawing Rights', ''),
(133, 'KES', 'Kenyan Shilling', 'KSh'),
(134, 'KGS', 'Kyrgyzstani Som', 'лв'),
(135, 'LRD', 'Liberian Dollar', '$'),
(136, 'MOP', 'Macanese Pataca', ''),
(137, 'MVR', 'Maldivian Rufiyaa', ''),
(138, 'MXN', 'Mexican Peso', '$'),
(139, 'NAD', 'Namibian Dollar', '$'),
(140, 'NOK', 'Norwegian Krone', 'kr'),
(141, 'PLN', 'Polish Zloty', 'zł'),
(142, 'RUB', 'Russian Ruble', 'руб'),
(143, 'SZL', 'Swazi Lilangeni', ''),
(144, 'TJS', 'Tajikistani Somoni', ''),
(145, 'TTD', 'Trinidad and Tobago Dollar', 'TT$'),
(146, 'UGX', 'Ugandan Shilling', 'USh'),
(147, 'UYU', 'Uruguayan Peso', '$U'),
(148, 'VND', 'Vietnamese Dong', 'â‚«'),
(149, 'TND', 'Tunisian Dinar', ''),
(150, 'UAH', 'Ukrainian Hryvnia', 'â‚´'),
(151, 'UZS', 'Uzbekistani Som', 'лв'),
(152, 'TMT', 'Turkmenistan Manat', ''),
(153, 'GBP', 'British Pound', '£'),
(154, 'ZMW', 'Zambian Kwacha', ''),
(155, 'BTC', 'Bitcoin', 'BTC'),
(156, 'BYN', 'New Belarusian Ruble', 'p.');

Step 2: Create currency converter form

Create index.php file that contains two select boxes one for the From currency, the second one is for the To Currency and the input field for the Amount that needs to be converted.

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<!-- jQuery END PART-->
<title>Currency Convertor Using PHP</title>
<!--custom javascript-->
<script src="script.js"></script>
<style>
.body {
	color:#FFFFFF;
}
.classWithPad {
	margin:2px;
	padding:4px;
}
#converted_amount_id {
	color:green;
}
input {
	height: 12px;
}
.table {
	margin-bottom:25px;
	width:30%;
	color:#FFFFFF;
	border:#FFFFFF solid 1px;
}
.table td, .table th {
	padding:5px;
	border:0px solid #FFFFFF;
}
.table th {
/*background:#f1f1f1;*/
}
</style>
<div class="content">
<div class="container-fluid">
  <h2>Currency Converter Using PHP</h2>
  <br>
  <br>
  <div class="row" style="background:#1C4678;">
    <h2 style="color:#FFFF00;">Currency Converter Using PHP</h2>
    <form class="form-inline" >
      <table class="table">
        <tr>
          <td>Amount</td>
          <td><input style="width:90px;" type="text" class="form-control" name="amount" id="amount_id" required>
          </td>
        </tr>
        <tr>
          <td>From Currency</td>
          <td><select class="form-control" id="from_currency_id" required name="from_currency" style="width:170px;">
              <?php include('db-connection.php');?>
              <?php  
              $sql_query = "SELECT currency_id,currency_name FROM currency_list";
             
              if ($result=mysqli_query($con,$sql_query))
              {
                 
                while ($currency_list = mysqli_fetch_assoc($result))
                { 
            ?>
              <option value="<?php echo $currency_list['currency_id'];?>" <?php if($currency_list['currency_id'] == "USD"){echo 'selected';}?> ><?php echo $currency_list['currency_name']; ?></option>
              <?php    } } ?>
            </select>
          </td>
        </tr>
        <tr>
          <td>To Currency</td>
          <td><select class="form-control" id="to_currency_id" name="to_currency" required style="width:170px;">
              <?php  
              $sql_query  = "SELECT currency_id,currency_name FROM currency_list";
              if ($result = mysqli_query($con,$sql_query))
              {
                 
                while ($currency_list = mysqli_fetch_assoc($result))
                { 
            ?>
              <option value="<?php echo $currency_list['currency_id'];?>" <?php if($currency_list['currency_id'] == "INR"){echo 'selected';}?>><?php echo $currency_list['currency_name']; ?></option>
              <?php    } } ?>
            </select>
          </td>
        </tr>
        <tr>
          <td>Converted Amount</td>
          <td><input style="width:90px;" type="text" class="form-control" id="converted_amount_id" readonly="">
          </td>
        </tr>
        <tr>
          <td colspan="2"><button type="button"  onclick="convertCurrency();" class="btn btn-danger">Convert</button></td>
      </table>
    </form>
  </div>
</div>

Step 3: Create currency-converter.php file

In the currency-converter.php file using the POST method, we get all the submitted form fields data and after that, we passed these data to convertCurrency() function.

Finally convertCurrency function makes the request to currencyconvertor.com API and it returns the converted amount in JSON format.

<?php
if(isset($_POST['from_currency']) && isset($_POST['to_currency'])  && isset($_POST['amount'])  )
{
	$from_currency 	= 	$_POST['from_currency'];
	$to_currency 	= 	$_POST['to_currency'];
	$amount 		= 	$_POST['amount'];
	if($from_currency == $to_currency)
	{	
		$response = array('error'=>1,'message'=>'From Currency & TO Currency Must be Different','converted_result'=>'');
		echo json_encode($response);
		die;
	}
	else
	{
		$converted_result = convertCurrency( $amount, $from_currency, $to_currency );
		$response = array('error'=>0,'message'=>'ok','converted_result'=>$converted_result);
		echo json_encode($response);
		die;
	}
}

function convertCurrency( $amount , $from_currency , $to_currency ){
  
  $from_Currency = urlencode($from_currency);
  $to_Currency = urlencode($to_currency);
  $query =  "{$from_Currency}_{$to_Currency}";
  #use your api key here
  $json = file_get_contents("http://free.currencyconverterapi.com/api/v6/convert?q={$query}&compact=ultra&apiKey=b0656342b804b366219c");
  $obj = json_decode($json, true);

  $val = floatval($obj["$query"]);
  $total = $val * $amount;
  
  return number_format($total, 2, '.', '');
}

?>

Conclusion :- In this tutorial we learnt how to create currency converter system using PHP .If you found any mistake in this tutorial please comment below.

Leave a Reply

Your email address will not be published. Required fields are marked *