Last active
September 25, 2019 07:42
-
-
Save LucaRosaldi/6951afe926cdbc4ea6f4213ed3d9ec41 to your computer and use it in GitHub Desktop.
PHP: Get User Geolocation with ipgeolocationapi.com
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Get the user IP address from the server request. | |
* | |
* @return string | |
*/ | |
function get_user_ip() : string { | |
if ( ! empty( $_SERVER['HTTP_CLIENT_IP'] ) ) { | |
return $_SERVER[ 'HTTP_CLIENT_IP' ]; | |
} | |
if ( ! empty( $_SERVER[ 'HTTP_X_FORWARDED_FOR' ] ) ) { | |
return $_SERVER[ 'HTTP_X_FORWARDED_FOR' ]; | |
} | |
return $_SERVER[ 'REMOTE_ADDR' ]; | |
} | |
/** | |
* Get user geolocation using the ipgeolocationapi.com API. | |
* | |
* @param string $ip_address | |
* @return stdClass The geolocation data results | |
*/ | |
function get_user_geolocation( string $ip_address ) : stdClass { | |
$url = "https://api.ipgeolocationapi.com/geolocate/$ip_address"; | |
$ch = curl_init(); | |
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 ); | |
curl_setopt( $ch, CURLOPT_URL, $url ); | |
$result = curl_exec( $ch ); | |
return json_decode( $result ); | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment