[ Penyelesaian ]
Enam masalah biasa yang boleh diselesaikan dengan satu semakan IP. Setiap satu disertakan senario, cara ia berfungsi langkah demi langkah, medan yang perlu dibaca dan kod yang boleh anda tampal ke dalam projek anda.
[ 01 — Penyetempatan ]
Senario
Seorang pelawat dari Kuala Lumpur tiba di laman utama bahasa Inggeris anda, melihat harga dalam USD dan sepanduk penghantaran untuk AS. Kebanyakan akan pergi sebelum menemui penukar bahasa.
Cara ia berfungsi
Medan yang akan anda gunakan
location.country.codelocation.country.namelocation.language.codelocation.country.calling_codelocation.in_euPetikan respons
{
"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']; // satu semakan bagi setiap lawatan
$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, // jangan sekali-kali menyekat halaman terlalu lama
]);
$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; // cth. "MY"
// <select name="country"> ... tandakan $country sebagai dipilih
// <html lang="<?= $lang ?>">
// Panggil laluan backend anda sendiri, yang menambah kunci API pada pelayan.
// Jangan sekali-kali letakkan kunci API anda dalam kod pelayar.
const res = await fetch('/geo'); // pelayan anda menjadi proksi kepada 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 — Pencegahan penipuan ]
Senario
Akaun palsu dan kad curi sering datang melalui VPN, proksi, Tor atau IP pusat data, atau dari negara yang tidak sepadan dengan alamat pengebilan.
Cara ia berfungsi
Medan yang akan anda gunakan
security.is_vpnsecurity.is_proxysecurity.is_torsecurity.is_threatsecurity.is_abusersecurity.is_cloud_providerlocation.country.codeconnection.typePetikan respons
{
"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']]; // gagal terbuka
$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(); // tingkatkan pengesahan, jangan terus sekat
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'] }; // gagal terbuka
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 — Mata wang & harga ]
Senario
Melihat "$49" membuatkan pelawat di Malaysia atau Jepun perlu mengira sendiri, dan ramai yang berputus asa. Mata wang dan format tempatan meningkatkan penukaran.
Cara ia berfungsi
Medan yang akan anda gunakan
currency.codecurrency.symbol_nativecurrency.format.positivecurrency.format.decimal_separatorcurrency.format.group_separatorPetikan respons
{
"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: # hanya mata wang yang anda sokong
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 = respons API (diambil pada pelayan anda)
const code = geo.currency?.code ?? 'USD';
const rate = rates[code]; // daripada sumber FX anda
const price = rate ? 49 * rate : 49;
// Intl membuat pemformatan untuk anda; API memberitahu mata wang yang mana
const label = new Intl.NumberFormat(navigator.language, {
style: 'currency', currency: rate ? code : 'USD',
}).format(price); // "RM 219.03"
[ 04 — Kawalan akses ]
Senario
Pelesenan, sekatan atau penyalahgunaan mungkin memaksa anda mengehadkan lokasi perkhidmatan anda digunakan, atau menyekat trafik tanpa nama pada halaman sensitif seperti pentadbir atau log masuk.
Cara ia berfungsi
Medan yang akan anda gunakan
location.country.codeconnection.asnsecurity.is_torsecurity.is_proxysecurity.is_anonymousPetikan respons
{
"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 minit
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(); // gagal terbuka (atau tertutup, terpulang kepada anda)
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
// sasaran auth_request: nginx bertanya kepada skrip ini sebelum menyajikan /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 — Analitik ]
Senario
Log akses mentah hanya menunjukkan alamat IP. Menukarnya kepada negara, bandar, ISP dan trafik perniagaan berbanding kediaman menunjukkan di mana anda patut memasarkan dan dari mana bot datang.
Cara ia berfungsi
Medan yang akan anda gunakan
location.country.codelocation.citylocation.region.nameconnection.asnconnection.organizationconnection.typecompany.namePetikan respons
{
"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: # hanya IP baharu yang memerlukan permintaan
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), ...]
-- Pendaftaran mengikut negara dan jenis sambungan bulan ini
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;
-- baris 'hosting' dengan banyak pendaftaran biasanya bot yang wajar diteliti
[ 06 — Zon waktu ]
Senario
Peringatan yang dihantar pada 9 pagi waktu pelayan tiba pada 1 pagi bagi separuh pengguna anda. Halaman tempahan yang memaparkan UTC mengelirukan semua orang.
Cara ia berfungsi
Medan yang akan anda gunakan
time_zone.idtime_zone.offsettime_zone.current_timetime_zone.in_daylight_savingtime_zone.abbreviationPetikan respons
{
"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
// semasa pendaftaran
$geo = lookup($clientIp); // fungsi pembantu API anda
$tz = $geo['time_zone']['id'] ?? 'UTC'; // "Asia/Kuala_Lumpur"
$db->prepare('UPDATE users SET timezone = ? WHERE id = ?')->execute([$tz, $userId]);
// paparkan cap masa UTC dalam waktu pengguna
$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"
// 09:00 tempatan seterusnya, dalam UTC, untuk baris gilir peringatan
$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 daripada respons API (disimpan semasa pendaftaran)
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"
[ Mula ]
Cipta akaun, salin kunci API anda ke dalam DKLY_API_KEY, dan setiap contoh di atas boleh terus digunakan.