execute('SET SESSION time_zone = \'+00:00\', sql_mode = \'STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION\';'); } catch(Exception $ex) { die((string)$ex); } define('EXRATE_INTER', 'EUR'); define('EXRATE_COMMON', [ 'EUR', 'AUD', 'GBP', 'CAD', 'USD', 'JPY', 'PLN', 'SGD', 'RUB', 'ILS', ]); $from = strtoupper((string)filter_input(INPUT_GET, 'from')); $to = strtoupper((string)filter_input(INPUT_GET, 'to')); $amount = (string)(filter_input(INPUT_GET, 'amount', FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION) ?? '1'); if((!empty($to) && strlen($to) !== 3) || strlen($from) !== 3) { http_response_code(400); die('Invalid currency specified.'); } $needsRefresh = $db->query('SELECT MAX(rate_stored) > NOW() - INTERVAL 1 DAY FROM `exchange-rates` LIMIT 1'); $needsRefresh->next(); $needsRefresh = $needsRefresh->isNull(0) || $needsRefresh->getInteger(0) < 1; if($needsRefresh) { $data = json_decode(file_get_contents('https://api.exchangerate.host/latest?base=' . EXRATE_INTER), true); if($data !== null) { $db->execute('TRUNCATE `exchange-rates`'); $insertCurrency = $db->prepare('INSERT INTO `exchange-rates` (rate_from, rate_to, rate_value) VALUES (?, ?, ?)'); foreach($data['rates'] as $currency => $rate) { $insertCurrency->reset(); $insertCurrency->addParameter(1, $data['base']); $insertCurrency->addParameter(2, $currency); $insertCurrency->addParameter(3, $rate); $insertCurrency->execute(); } } } $result = new stdClass; $result->from = $from; $result->to = $to; $result->amount = (float)$amount; if($from === $to) { $result->result = $result->amount; } else { $convertCurrency = $db->prepare(sprintf( 'SELECT (SELECT (? / rate_value) FROM `exchange-rates` WHERE rate_from = "%1$s" AND rate_to = ?) * rate_value FROM `exchange-rates` WHERE rate_from = "%1$s" AND rate_to = ?', EXRATE_INTER )); if(empty($to)) { $result->results = []; foreach(EXRATE_COMMON as $commonCurrency) { if($commonCurrency === $from) continue; $result->results[] = $current = new stdClass; $current->to = $commonCurrency; $convertCurrency->reset(); $convertCurrency->addParameter(1, $amount); $convertCurrency->addParameter(2, $from); $convertCurrency->addParameter(3, $commonCurrency); $convertCurrency->execute(); $convertResult = $convertCurrency->getResult(); $convertResult->next(); $current->result = $convertResult->getFloat(0); } } else { $convertCurrency->addParameter(1, $amount); $convertCurrency->addParameter(2, $from); $convertCurrency->addParameter(3, $to); $convertCurrency->execute(); $convertResult = $convertCurrency->getResult(); $convertResult->next(); $result->result = $convertResult->getFloat(0); } } http_response_code(200); header('Content-Type: application/json'); echo json_encode($result);