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.4 KiB
PHP

<?php
/*
* Copyright 2020 Netsyms Technologies.
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
header("Content-Type: application/json");
$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"];
}
use GeoIp2\Database\Reader;
use GeoIp2\Exception\AddressNotFoundException;
try {
$reader = new Reader($SETTINGS["geoip_database"]);
$record = $reader->city($clientip);
sendJsonResp(null, "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) {
sendJsonResp("Location not found for IP address.", "ERROR", ["clientip" => $clientip]);
}