Redirect visitors based on their location — PHP Code
1 min readJun 10, 2020
- Find the IP address of your visitor. The code below is for demonstration purposes only. It is not recommended as a copy paste replacement unless you know what you are doing [see (i)].
function get_client_ip() {
if (isset($_SERVER['HTTP_CLIENT_IP']))
$ip = $_SERVER['HTTP_CLIENT_IP'];
else if(isset($_SERVER['HTTP_X_FORWARDED_FOR']))
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
else if(isset($_SERVER['HTTP_X_FORWARDED']))
$ip = $_SERVER['HTTP_X_FORWARDED'];
else if(isset($_SERVER['HTTP_X_CLUSTER_CLIENT_IP']))
$ip = $_SERVER['HTTP_X_CLUSTER_CLIENT_IP'];
else if(isset($_SERVER['HTTP_FORWARDED_FOR']))
$ip = $_SERVER['HTTP_FORWARDED_FOR'];
else if(isset($_SERVER['HTTP_FORWARDED']))
$ip = $_SERVER['HTTP_FORWARDED'];
else if(isset($_SERVER['REMOTE_ADDR']))
$ip = $_SERVER['REMOTE_ADDR'];
else
$ip = '';
return $ip;
}
2. Find the location of the IP address of your visitor. The code sample below requires an API key. You can contact us for a trial API key if you need one.
$APIKEY = ‘Required here’;$ip = get_client_ip();
$country = file_get_contents(‘https://ipapi.co/'.$ip.'/country/?key='.$APIKEY);
3. Redirect visitor based on the country received above. The example below uses a temporary redirect (HTTP status code 302).
if ($country == 'UK')
header('Location: https://example.com/uk', true, 302);
else if ($country == 'FR')
header('Location: https://example.com/fr', true, 302);
else if ($country == 'US')
header('Location: https://example.com/us', true, 302);
else
header('Location: https://example.com/world', true, 302);