Country detection via PHP

- 1 min read

Imagine a example.com with some example.com/es, example.com/fr with content related to each country. One solution is a javascript-based country detector that could ask the visitor to change the current site to the most appropriate one regarding to the visitors origin. The problem with this solution is that the user needs to load the content twice, and is not a very good experience.

With a index.php-based PHP country detection we can use a fast external API to determine the visitors country and redirect to the specific location, and if no country is detected, redirect it to a default site.

Well, for this job we could use ipinfo.io, this website offers a very fast and free API (with limits, but if you are going to use in a small-medium site is enought) that returns all the data in JSON.

/**
 * Runs the country detection
 */
function country_detection() {

	$current_sites_list = array(
		'au',
		'uk'
	);
	$visitor_ip         = $_SERVER['REMOTE_ADDR'];
	$ch                 = curl_init();

	curl_setopt( $ch, CURLOPT_URL, 'https://ipinfo.io/' . $visitor_ip );
	curl_setopt( $ch, CURLOPT_TIMEOUT, 3 );
	curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );

	$output          = curl_exec( $ch );
	$current_country = strtolower( json_decode( $output )->country );

	curl_close( $ch );

	header( 'HTTP/1.1 302 Found' );

	if ( in_array( $current_country, $current_sites_list ) ) {
		header( 'Location: https://' . $_SERVER['SERVER_NAME'] . '/' . $current_country . '/' );
	} else {
		header( 'Location: https://' . $_SERVER['SERVER_NAME'] . '/' );
	}

	exit;
}

if ( $_SERVER['REQUEST_URI'] == '/' ) {
	country_detection();
}

Share: Link copied to clipboard

Tags:

Previous: Basic flexbox structure
Next: The Bechdel-Wallace test

Where: Home > Technical > Country detection via PHP