Advertisement
Redirecting users according to their country TLD
Today, I am going to teach you how to redirect users to their country TLD using simple PHP.
for example:
If visitor is from UK:
http://example.com/members/usercp/avatars.php –> http://example.co.uk/members/usercp/avatars.php
And if visior is from a country whose TLD is .com :
Dont redirect anywhere.
To get started, you must have a GEO-Location script to determine the Location of visitor and their country TLD.
For example:
Canada –> .ca
USA –> .us
Australia –> .au
United Kingdom –> .co.uk
Some country –> .com
Suppose your script assigns the TLD to a variable called $tld.
Now we are supposing that the visitor is from United Kingdom, so the value of $tld is .co.uk here.
Now we need a script to redirect them, if $tld doesnt have .com as its value.
To do this, write this code in a new file called redirect.php :
PHP Code:
<?php
$current_url = $_SERVER['PHP_SELF'];
$redirect = str_replace(”.com”, $tld, $current_url);
if ($tld != ‘.com’) {
header(”Location: $redirect”);
}
?>
In this code, we first assigned the value of $redirect by replacing “.com” in $current_url (which has value of the whole URL of current location) with $tld (which is now .co.uk).
Now on every page you want to redirect, on top of anything, write this code:
PHP Code:
<?php
include_once ("Path-to-redirect.php");
?>
where the Path-to-redirect.php is the absolute path to file, i-e: “includes/redirect.php”
This code will redirect the user to the TLD of their country, without changing the URL , for example :
http://example.com/members/usercp/avatars.php –> http://example.co.uk/members/usercp/avatars.php
The above action will only be performed if the user is not in a country whose TLD is .com (which you can assign in geo location script).