PHPでIPジオロケーションを取得するガイド
PHPで1つのIPアドレスの国、都市、おおよその座標を取得します。
PHPでIPアドレスを検索する
リクエストにはIPv4またはIPv6アドレスを1つ指定し、JSONを要求します。サンプルのアドレスを、調査するアドレスに置き換えてください。
<?php
$ip = '8.8.8.8'; // Replace with a validated IPv4 or IPv6 address.
if (!filter_var($ip, FILTER_VALIDATE_IP)) {
throw new InvalidArgumentException('Invalid IP address');
}
$url = 'https://api.ipquery.io/' . rawurlencode($ip) . '?format=json';
$handle = curl_init($url);
curl_setopt_array($handle, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CONNECTTIMEOUT => 3,
CURLOPT_TIMEOUT => 8,
]);
$body = curl_exec($handle);
$status = curl_getinfo($handle, CURLINFO_HTTP_CODE);
if ($body === false) {
$error = curl_error($handle);
throw new RuntimeException('IP lookup failed: ' . $error);
}
if ($status !== 200) {
throw new RuntimeException('IPQuery returned HTTP ' . $status);
}
$data = json_decode($body, true, 512, JSON_THROW_ON_ERROR);
if (($data['ip'] ?? null) !== $ip || !isset($data['location']) || !is_array($data['location'])) {
throw new RuntimeException('Unexpected IPQuery response');
}
$location = $data['location'];
$countryCode = strtoupper(trim((string) ($location['country_code'] ?? '')));
$city = trim((string) ($location['city'] ?? ''));
echo 'Country code: ' . ($countryCode ?: 'Unknown') . PHP_EOL;
echo 'City: ' . ($city ?: 'Unknown') . PHP_EOL;
// Coordinates describe an approximate network location, not the user.
$latitude = $location['latitude'] ?? null;
$longitude = $location['longitude'] ?? null;
if (preg_match('/^[A-Z]{2}$/', $countryCode) &&
!in_array($countryCode, ['XX', 'ZZ'], true) &&
is_numeric($latitude) && is_numeric($longitude)) {
printf('Approximate coordinates: %.5f, %.5f%s', $latitude, $longitude, PHP_EOL);
}cURL拡張を有効にしたPHPが必要です。接続タイムアウトは3秒、リクエスト全体の時間制限は8秒です。
位置情報フィールドを読み取る
location.country_codeは2文字の国コード、location.countryは国名です。国が判明していてもlocation.cityが空の場合があります。空の値は不明のまま扱ってください。
location.latitudeとlocation.longitudeはネットワークの所在地を示すおおよその座標です。表示する前に、利用できる地名が存在することを確認してください。数値の座標だけでは所在地を確定できません。端末や個人を特定するものではありません。
リクエストの接続元アドレスを取得するには、次を呼び出します: https://api.ipquery.io/?format=json. サーバーからのリクエストではサーバーの接続元IPが返り、ブラウザーからのリクエストではその接続の外部から見えるアドレスが返ります。
精度とセキュリティ
IPジオロケーションはネットワークの所在地の推定であり、端末の位置ではありません。VPN、プロキシ、モバイルネットワーク、通信事業者のゲートウェイにより、アドレスがユーザーから遠く離れた場所に位置付けられる場合があります。欠けている値を推測で補わず、不明として扱ってください。
アプリケーションがX-Forwarded-Forを読み取る場合は、自分で管理するプロキシが付与した値だけを信頼してください。クライアントが送信したヘッダーは偽装できます。検索リクエストの前にアドレスを検証し、タイムアウトとHTTPエラーは成功した結果とは別に処理してください。
APIリファレンス