You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

40 lines
1.2 KiB
PHP

<?php
$clientip = $_SERVER["REMOTE_ADDR"];
// Don't do this if the IP matters for security, unless you verify REMOTE_ADDR
// is an address inside Cloudflare's CDN. It's fine here though, since we're
// just turning it into a lat/lon using publicly-available data.
if (!empty($_SERVER["HTTP_CF_CONNECTING_IP"])) {
$clientip = $_SERVER["HTTP_CF_CONNECTING_IP"];
}
if (!empty($VARS["ip"])) {
$clientip = $VARS["ip"];
}
use GeoIp2\Database\Reader;
use GeoIp2\Exception\AddressNotFoundException;
try {
$reader = new Reader(env("geoip_database"));
$record = $reader->city($clientip);
exitWithJson([
"status" => "OK",
"location" => [
"latitude" => $record->location->latitude,
"longitude" => $record->location->longitude
],
"clientip" => $clientip,
"postcode" => $record->postal->code,
"attribution" => "This product includes GeoLite2 data created by MaxMind, available from <a href=\"https://www.maxmind.com\">https://www.maxmind.com</a>."
]);
} catch (GeoIp2\Exception\AddressNotFoundException $ex) {
exitWithJson([
"status" => "ERROR",
"message" => "Location not found for IP address.",
"clientip" => $clientip
]);
}