Skip to content

Commit 4ac870c

Browse files
committed
feat: add support for ip geolocation
1 parent 61e0f83 commit 4ac870c

File tree

1 file changed

+48
-5
lines changed

1 file changed

+48
-5
lines changed

src/Request.php

Lines changed: 48 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -726,15 +726,58 @@ public static function getFullUrl(): string
726726
*/
727727
public static function getIp(): string
728728
{
729-
$keys = ['X_FORWARDED_FOR', 'HTTP_X_FORWARDED_FOR', 'CLIENT_IP', 'REMOTE_ADDR'];
729+
return $_SERVER['HTTP_CLIENT_IP']
730+
?? $_SERVER['HTTP_X_FORWARDED_FOR']
731+
?? $_SERVER['REMOTE_ADDR'];
732+
}
730733

731-
foreach ($keys as $key) {
732-
if (isset($_SERVER[$key])) {
733-
return $_SERVER[$key];
734+
/**
735+
* Get Current User Location using IP
736+
* @see https://ip-api.com/docs/api:json
737+
* @uses \Leaf\Http\Request::getLocationFromIp
738+
* @return array
739+
*/
740+
public static function getUserLocation(): array
741+
{
742+
return static::getLocationFromIp(
743+
static::getIp()
744+
);
745+
}
746+
747+
/**
748+
* Get IP-based Location using ip-api
749+
* @see https://ip-api.com/docs/api:json
750+
* @return array
751+
*/
752+
public static function getLocationFromIp(string $ip): array
753+
{
754+
$response = [
755+
'country' => null,
756+
'countryCode' => null,
757+
'region' => null,
758+
'regionName' => null,
759+
'currency' => null,
760+
'city' => null,
761+
'zip' => null,
762+
'lat' => null,
763+
'lon' => null,
764+
'timezone' => null,
765+
'ip' => $ip,
766+
'continent' => null,
767+
'continentCode' => null,
768+
];
769+
770+
try {
771+
$res = file_get_contents("http://ip-api.com/json/{$response['ip']}?fields=status,continent,continentCode,country,countryCode,region,regionName,city,zip,lat,lon,timezone,currency,query");
772+
$data = json_decode($res ?? '{}', true);
773+
774+
if (($data['status'] ?? false) === 'success') {
775+
$response = array_merge($response, $data);
734776
}
777+
} catch (\Exception $e) {
735778
}
736779

737-
return $_SERVER['REMOTE_ADDR'];
780+
return $response;
738781
}
739782

740783
/**

0 commit comments

Comments
 (0)