Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
<?php
require_once 'vendor/autoload.php';
use GeoIp2\Database\Reader;
/**
* Returns the visitors IP address.
* @return string
*/
function get_visitor_IP() {
$ip = null;
$client = @$_SERVER['HTTP_CLIENT_IP'];
$forward = @$_SERVER['HTTP_X_FORWARDED_FOR'];
$remote = $_SERVER['REMOTE_ADDR'];
if ( filter_var( $client, FILTER_VALIDATE_IP ) ) {
$ip = $client;
} elseif ( filter_var( $forward, FILTER_VALIDATE_IP ) ) {
$ip = $forward;
} else {
$ip = $remote;
}
return $ip;
}
/**
* Returns the GeoIp2 Reader instance.
* @return Reader
*/
function get_geoip2_reader() {
return new Reader( get_template_directory() . '/GeoLite2-Country.mmdb' );
}
/**
* Returns the visitors country code.
* @return null|string
*/
function get_geoip2_country_code( $ip ) {
$result = null;
try {
$reader = get_geoip2_reader();
$result = $reader->country( $ip )->country->isoCode;
} catch (\Exception $e) {
// handle the exception
}
return $result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.