Skip to content

Instantly share code, notes, and snippets.

@LucaRosaldi
Last active September 25, 2019 07:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LucaRosaldi/6951afe926cdbc4ea6f4213ed3d9ec41 to your computer and use it in GitHub Desktop.
Save LucaRosaldi/6951afe926cdbc4ea6f4213ed3d9ec41 to your computer and use it in GitHub Desktop.
PHP: Get User Geolocation with ipgeolocationapi.com
<?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