[ Solutions ]
Six common problems that one IP lookup solves. Each has the scenario, how it works step by step, the fields to read, and code you can paste into your project.
[ 01 — Localization ]
The scenario
A visitor from Kuala Lumpur lands on your English homepage, sees prices in USD and a shipping banner for the US. Most will leave before they find the language switcher.
How it works
Fields you'll use
location.country.codelocation.country.namelocation.language.codelocation.country.calling_codelocation.in_euResponse excerpt
{
"location": {
"country": {
"code": "MY",
"name": "Malaysia",
"calling_code": "60"
},
"language": {
"code": "ms",
"name": "Malay"
},
"in_eu": false
}
}
<?php
session_start();
function visitorGeo(): ?array {
if (isset($_SESSION['geo'])) return $_SESSION['geo']; // one lookup per visit
$ip = $_SERVER['HTTP_CF_CONNECTING_IP'] ?? $_SERVER['REMOTE_ADDR'];
$ch = curl_init('https://ipinfo.dkly.net/api/?ip=' . urlencode($ip));
curl_setopt_array($ch, [
CURLOPT_HTTPHEADER => ['X-API-Key: ' . getenv('DKLY_API_KEY')],
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 2, // never block the page for long
]);
$res = json_decode(curl_exec($ch) ?: 'null', true);
return $_SESSION['geo'] = is_array($res) && isset($res['location']) ? $res : null;
}
$geo = visitorGeo();
$supported = ['en', 'ms', 'zh', 'ja', 'th'];
$lang = $geo['location']['language']['code'] ?? 'en';
$lang = in_array($lang, $supported, true) ? $lang : 'en';
$country = $geo['location']['country']['code'] ?? null; // e.g. "MY"
// <select name="country"> ... mark $country as selected
// <html lang="<?= $lang ?>">
// Call your own backend route, which adds the API key on the server.
// Never put your API key in browser code.
const res = await fetch('/geo'); // your server proxies ipinfo.dkly.net/api/
const geo = await res.json();
const country = geo.location?.country?.code; // "MY"
const lang = geo.location?.language?.code ?? 'en'; // "ms"
document.querySelector('#country').value = country ?? '';
if (!localStorage.lang && lang !== document.documentElement.lang) {
showBanner(`View this site in ${geo.location.language.name}?`, () => switchLang(lang));
}
[ 02 — Fraud prevention ]
The scenario
Fake accounts and stolen cards often come through VPNs, proxies, Tor or data-center IPs, or from a country that doesn't match the billing address.
How it works
Fields you'll use
security.is_vpnsecurity.is_proxysecurity.is_torsecurity.is_threatsecurity.is_abusersecurity.is_cloud_providerlocation.country.codeconnection.typeResponse excerpt
{
"security": {
"is_vpn": true,
"is_proxy": false,
"is_tor": false,
"is_threat": false,
"is_cloud_provider": true
},
"connection": {
"type": "hosting"
}
}
<?php
function ipRisk(string $ip, ?string $billingCountry = null): array {
$ch = curl_init('https://ipinfo.dkly.net/api/?ip=' . urlencode($ip));
curl_setopt_array($ch, [CURLOPT_HTTPHEADER => ['X-API-Key: ' . getenv('DKLY_API_KEY')],
CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 3]);
$d = json_decode(curl_exec($ch) ?: 'null', true);
if (!isset($d['security'])) return ['score' => 0, 'reasons' => ['lookup_failed']]; // fail open
$s = $d['security']; $score = 0; $why = [];
$add = function (bool $hit, int $pts, string $r) use (&$score, &$why) { if ($hit) { $score += $pts; $why[] = $r; } };
$add($s['is_tor'] ?? false, 50, 'tor');
$add($s['is_threat'] ?? false, 40, 'known_threat');
$add($s['is_proxy'] ?? false, 30, 'proxy');
$add($s['is_vpn'] ?? false, 20, 'vpn');
$add($s['is_cloud_provider'] ?? false, 20, 'datacenter');
$add($billingCountry && ($d['location']['country']['code'] ?? null) !== $billingCountry, 25, 'country_mismatch');
return ['score' => $score, 'reasons' => $why];
}
$risk = ipRisk($_SERVER['HTTP_CF_CONNECTING_IP'] ?? $_SERVER['REMOTE_ADDR'], $order['billing_country']);
if ($risk['score'] >= 70) reject('Please contact support to complete this order.');
elseif ($risk['score'] >= 30) requireOtp(); // step-up, don't block outright
const API = 'https://ipinfo.dkly.net/api/';
export async function ipRisk(ip, billingCountry) {
const r = await fetch(`${API}?ip=${encodeURIComponent(ip)}`, {
headers: { 'X-API-Key': process.env.DKLY_API_KEY },
signal: AbortSignal.timeout(3000),
}).catch(() => null);
if (!r?.ok) return { score: 0, reasons: ['lookup_failed'] }; // fail open
const d = await r.json(), s = d.security ?? {};
const rules = [
[s.is_tor, 50, 'tor'], [s.is_threat, 40, 'known_threat'], [s.is_proxy, 30, 'proxy'],
[s.is_vpn, 20, 'vpn'], [s.is_cloud_provider, 20, 'datacenter'],
[billingCountry && d.location?.country?.code !== billingCountry, 25, 'country_mismatch'],
];
const hits = rules.filter(([hit]) => hit);
return { score: hits.reduce((n, [, p]) => n + p, 0), reasons: hits.map(([, , why]) => why) };
}
[ 03 — Currency & pricing ]
The scenario
Seeing "$49" makes a visitor in Malaysia or Japan do mental maths, and many give up. Local currency and formatting raise conversion.
How it works
Fields you'll use
currency.codecurrency.symbol_nativecurrency.format.positivecurrency.format.decimal_separatorcurrency.format.group_separatorResponse excerpt
{
"currency": {
"code": "MYR",
"symbol_native": "RM",
"format": {
"decimal_separator": ".",
"group_separator": ",",
"positive": {
"prefix": "RM",
"suffix": ""
}
}
}
}
import os, requests
def local_price(ip: str, usd: float, rates: dict) -> str:
r = requests.get("https://ipinfo.dkly.net/api/", params={"ip": ip},
headers={"X-API-Key": os.environ["DKLY_API_KEY"]}, timeout=2)
cur = r.json().get("currency") or {}
code = cur.get("code", "USD")
if code not in rates: # only currencies you support
code, cur = "USD", {"format": {"positive": {"prefix": "$", "suffix": ""},
"decimal_separator": ".", "group_separator": ","}}
amount = usd * rates.get(code, 1.0)
f = cur["format"]
whole, frac = f"{amount:,.2f}".split(".")
whole = whole.replace(",", f["group_separator"])
return f'{f["positive"]["prefix"]}{whole}{f["decimal_separator"]}{frac}{f["positive"]["suffix"]}'
# local_price("111.221.48.163", 49, {"USD": 1, "MYR": 4.47}) -> "RM219.03"
// geo = the API response (fetched on your server)
const code = geo.currency?.code ?? 'USD';
const rate = rates[code]; // from your FX source
const price = rate ? 49 * rate : 49;
// Intl does the formatting for you; the API tells you which currency
const label = new Intl.NumberFormat(navigator.language, {
style: 'currency', currency: rate ? code : 'USD',
}).format(price); // "RM 219.03"
[ 04 — Access control ]
The scenario
Licensing, sanctions or abuse may force you to limit where your service is used, or to block anonymous traffic on sensitive pages such as admin or login.
How it works
Fields you'll use
location.country.codeconnection.asnsecurity.is_torsecurity.is_proxysecurity.is_anonymousResponse excerpt
{
"location": {
"country": {
"code": "MY"
}
},
"connection": {
"asn": 38278
},
"security": {
"is_tor": false,
"is_proxy": false,
"is_anonymous": false
}
}
import express from 'express';
const cache = new Map(); // ip -> { d, t }
const ALLOWED = new Set(['MY', 'SG', 'ID', 'TH']);
async function lookup(ip) {
const hit = cache.get(ip);
if (hit && Date.now() - hit.t < 10 * 60_000) return hit.d; // 10 min
const r = await fetch(`https://ipinfo.dkly.net/api/?ip=${ip}`, {
headers: { 'X-API-Key': process.env.DKLY_API_KEY },
});
const d = r.ok ? await r.json() : null;
cache.set(ip, { d, t: Date.now() });
return d;
}
export async function geoGate(req, res, next) {
const ip = req.get('CF-Connecting-IP') ?? req.ip;
const d = await lookup(ip);
if (!d) return next(); // fail open (or closed, your call)
if (d.security?.is_tor || d.security?.is_proxy) return res.status(403).send('Anonymous proxies are not allowed here.');
if (!ALLOWED.has(d.location?.country?.code)) return res.status(403).send('This service is not available in your region.');
next();
}
app.use('/admin', geoGate);
<?php
// auth_request target: nginx asks this script before serving /admin
// location /admin { auth_request /geo-check.php; ... }
$ip = $_SERVER['HTTP_CF_CONNECTING_IP'] ?? $_SERVER['REMOTE_ADDR'];
$key = 'geo:' . $ip;
$d = apcu_fetch($key);
if ($d === false) {
$ctx = stream_context_create(['http' => ['header' => 'X-API-Key: ' . getenv('DKLY_API_KEY'), 'timeout' => 2]]);
$d = json_decode(@file_get_contents('https://ipinfo.dkly.net/api/?ip=' . urlencode($ip), false, $ctx) ?: 'null', true);
apcu_store($key, $d, 600);
}
$ok = $d && !($d['security']['is_tor'] ?? false) && in_array($d['location']['country']['code'] ?? '', ['MY', 'SG'], true);
http_response_code($ok ? 204 : 403);
[ 05 — Analytics ]
The scenario
Raw access logs only show IP addresses. Turning them into countries, cities, ISPs and business vs. residential traffic shows you where to market and where bots come from.
How it works
Fields you'll use
location.country.codelocation.citylocation.region.nameconnection.asnconnection.organizationconnection.typecompany.nameResponse excerpt
{
"location": {
"city": "Kuala Lumpur",
"region": {
"name": "Wilayah Persekutuan Kuala Lumpur"
},
"country": {
"code": "MY"
}
},
"connection": {
"asn": 38278,
"organization": "Orient Telecoms Sdn. Bhd",
"type": "isp"
}
}
import os, sqlite3, requests, collections
db = sqlite3.connect("geo.db")
db.execute("CREATE TABLE IF NOT EXISTS ip_geo (ip TEXT PRIMARY KEY, country TEXT, city TEXT, asn INT, org TEXT, type TEXT)")
s = requests.Session()
s.headers["X-API-Key"] = os.environ["DKLY_API_KEY"]
ips = {line.split()[0] for line in open("/var/log/nginx/access.log")}
known = {r[0] for r in db.execute("SELECT ip FROM ip_geo")}
for ip in ips - known: # only new IPs cost a request
d = s.get("https://ipinfo.dkly.net/api/", params={"ip": ip}, timeout=5).json()
loc, con = d.get("location", {}), d.get("connection", {})
db.execute("INSERT OR REPLACE INTO ip_geo VALUES (?,?,?,?,?,?)",
(ip, (loc.get("country") or {}).get("code"), loc.get("city"),
con.get("asn"), con.get("organization"), con.get("type")))
db.commit()
top = db.execute("SELECT country, COUNT(*) FROM ip_geo GROUP BY country ORDER BY 2 DESC LIMIT 10").fetchall()
print(top) # [('MY', 1840), ('SG', 610), ('US', 402), ...]
-- Signups per country and connection type this month
SELECT g.country, g.type, COUNT(*) AS signups
FROM signups s
JOIN ip_geo g ON g.ip = s.ip
WHERE s.created_at >= DATE_FORMAT(NOW(), '%Y-%m-01')
GROUP BY g.country, g.type
ORDER BY signups DESC;
-- 'hosting' rows with many signups are usually bots worth a closer look
[ 06 — Timezone ]
The scenario
A reminder sent at 9am server time lands at 1am for half your users. Booking pages showing UTC confuse everyone.
How it works
Fields you'll use
time_zone.idtime_zone.offsettime_zone.current_timetime_zone.in_daylight_savingtime_zone.abbreviationResponse excerpt
{
"time_zone": {
"id": "Asia/Kuala_Lumpur",
"abbreviation": "GMT+08:00",
"offset": 28800,
"in_daylight_saving": false,
"current_time": "2026-12-02T21:30:00+08:00"
}
}
<?php
// at sign-up
$geo = lookup($clientIp); // your API helper
$tz = $geo['time_zone']['id'] ?? 'UTC'; // "Asia/Kuala_Lumpur"
$db->prepare('UPDATE users SET timezone = ? WHERE id = ?')->execute([$tz, $userId]);
// show a UTC timestamp in the user's time
$when = new DateTime($row['starts_at_utc'], new DateTimeZone('UTC'));
$when->setTimezone(new DateTimeZone($user['timezone']));
echo $when->format('D j M, H:i T'); // "Wed 2 Dec, 21:30 +08"
// next 09:00 local, as UTC, for the reminder queue
$next = new DateTime('tomorrow 09:00', new DateTimeZone($user['timezone']));
$next->setTimezone(new DateTimeZone('UTC'));
queueEmail($userId, $next->format('Y-m-d H:i:s'));
// tz from the API response (saved at sign-up)
const tz = geo.time_zone?.id ?? Intl.DateTimeFormat().resolvedOptions().timeZone;
const fmt = new Intl.DateTimeFormat('en-GB', {
timeZone: tz, weekday: 'short', day: 'numeric', month: 'short',
hour: '2-digit', minute: '2-digit', timeZoneName: 'short',
});
fmt.format(new Date('2026-12-02T13:30:00Z')); // "Wed 2 Dec, 21:30 GMT+8"
[ Get started ]
Create an account, copy your API key into DKLY_API_KEY, and every example above works as-is.