Automatic Redirect Depending on Users Language - php

OBJECTIVE
I'm trying to accomplish an automatic redirect depending on the users language. I have a fully working code for that:
// List of available localized versions as 'lang code' => 'url' map
$sites = array(
"da" => "http://www.fredrixdesign.com/",
"en" => "http://en.fredrixdesign.com/"
);
// Get 2 char lang code
$lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
// Set default language if a `$lang` version of site is not available
if (!in_array($lang, array_keys($sites)))
$lang = 'en';
// Finally redirect to desired location
header('Location: ' . $sites[$lang]);
?>
This redirects the user to a Danish (da) version, which is the main/root website, if the user is Danish. If the user is German, English, Polish, etc. it redirects the user to a subdomain; en.fredrixdesign.com, which is an English version of the website.
But the problem occurs, when a Danish-user goes on my site. The code, located in the top of my header.php, keep getting executed, which means, it keeps creating the redirect, which finally forces the browser to create an error due to too many redirects. This makes sence.
QUESTION
My question is then; how would I go around modifying the above code, so it only executes the redirect once? If it just completed the redirect, it will simply continue to execute the site.

Well, I bet you can find a solution yourself if just think it over a bit.
All you need is to check if current domain meets desired language.
Just amend your array a bit
$sites = array(
"da" => "www.fredrixdesign.com",
"en" => "en.fredrixdesign.com"
);
and then add a condition for the redirect
if ($sites[$lang] != $_SERVER['HTTP_HOST']) {
header('Location: http://' . $sites[$lang] . '/');
exit;
}
that's all

You could set a cookie value, that tells you that you have already automatically redirected the user to a language-specific site. If that cookie exists, do not do the redirect again. You may also wish to consider the case where the user has cookies disabled.

You could do this with GeoIP + .htaccess, it's really easy to implement.
http://www.maxmind.com/app/mod_geoip

Something like this could do the trick (of course there are tons of heavy good solution but for two languages there is no harm to do simple things and improve later when needed):
function redirectIfUserIsNotOnTheGoodURLBasedOnHisLanguage()
{
// List of available localized versions as 'lang code' => 'url' map
$sites = array(
"da" => "http://www.fredrixdesign.com/",
"en" => "http://en.fredrixdesign.com/"
);
// Get 2 char lang code
$lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
// Set default language if a `$lang` version of site is not available
if (!in_array($lang, array_keys($sites)))
$lang = 'en';
if (($lang == 'da' && $_SERVER['SERVER_NAME'] == 'www.fredrixdesign.com') || // Danish people are on the right place
($lang == 'en' && $_SERVER['SERVER_NAME'] == 'en.fredrixdesign.com')) // Other people are on the right place
{
// no redirection
return;
}
// else redirect to desired location
header('Location: ' . $sites[$lang]);
exit(0);
}
redirectIfUserIsNotOnTheGoodURLBasedOnHisLanguage();

Related

recognize which language site customer came from to make correct redirect

I have the below code which lets a user log out from my Wordpress website without going via a separate page to confirm he wants to log out. The redirect is set to a custom my-account page where he can log in again or create an account.
However, I run a multilingual site (WPML). My English page is mydomain.com/my-account/ and the Italian equivalent would be mydomain.com/it/my-account/ etc. (I have about 7 languages). How can I modify the below code so that the language the person came from is remembered and the redirect includes the correct extension /it/ or /de/ etc.
add_action('check_admin_referer', 'logout_without_confirm', 10, 2);
function logout_without_confirm($action, $result)
{
if ($action == "log-out" && !isset($_GET['_wpnonce'])) {
$redirect_to = isset($_REQUEST['redirect_to']) ? $_REQUEST['redirect_to'] : '/my-account/';
$location = str_replace('&', '&', wp_logout_url($redirect_to));
header("Location: $location");
die;
}
}

How to create multi-regional website using wordpress

I'm trying to make a multi-regional website using WordPress. i'm working on url http://localhost/siteone I want when someone come from usa redirect to the localhost/siteone/usa/
I edit the function.php file of wordpress theme with code below, but getting error the url become localhost/siteone/usa/usa/usa/usa
// Detacting user location using ipstack
$json = file_get_contents('http://api.ipstack.com/check?access_key=ACCESSKEY&language=en');
// Converts it into a PHP object
$data = json_decode($json);
$loc = $data->country_code;
//NA = northamerica
//End of Decating user location
if($loc=="NA"){ header("Location: usa/"); }
This works very well sidealone but when I add in function.php in theme file not working and give me a error. what should I do. Should i use some session or anything eles.
It looks like it's trying to redirect multiple times, since it'll check the person's location, then redirect, then after redirecting it'll check again, and redirect again, etc.
What you could do is check whether "/usa" is already in the page URL, and if not, redirect, something like this could work:
if ($loc === "NA" && strpos($_SERVER['REQUEST_URI'],'usa/') === false) {
header("Location: usa/");
}
$_SERVER['REQUEST_URI'] is the URL of the current page, not including the domain.
For languages and create diferents regionals website, I'd recommend you this plugins (pro):
https://polylang.pro/ (just one paid)
enter link description here (anual fee)
Custom code based on language:
<?php
if(pll_current_language() == 'en') {
echo 'Only in english';
} else if(pll_current_language() == 'fr') {
echo 'Seulment en francais';
}
?>
If you prefer control language throught web server, use better: $_SERVER['HTTP_ACCEPT_LANGUAGE']
Link: https://www.php.net/manual/en/locale.acceptfromhttp.php
Regards!

Auto detect language and redirect user

I am doing my own website and I managed to write some code that makes directs user to the language version according to the browser's language. Here is the script:
<?php
if ($_SERVER["HTTP_ACCEPT_LANGUAGE"] == "sv")
header("location: index.php");
if ($_SERVER["HTTP_ACCEPT_LANGUAGE"] == "pt")
header("location: pt/index.php");
else
header("location: en/index.html");
?>
I have put this in the index.php before the . It seems to be working because I am not in an English speaking country but my browser is in English and I am being redirected to the English version.
Is this correct? Is there a better/cleaner way to do this?
PHP 5.3.0+ comes with locale_accept_from_http() which gets the preferred language from the Accept-Language header.
You should always prefer this method to a self-written method as the header field is more complicated than one might think. (It's a list of weighted preferences.)
You should retrieve the language like this:
$lang = locale_accept_from_http($_SERVER['HTTP_ACCEPT_LANGUAGE']);
But even then, you won't just have en for every English user and es for Spanish ones. It can become much more difficult than that, and things like es-ES and es-US are standard.
This means you should iterate over a list of regular expressions that you try and determine the page language that way. See PHP-I18N for an example.
Well, I came across some problems with my code which is no surprise due to I am not a PHP expert. I kept therefore on searching for a possible solution and I found the following code on another website:
<?php
// Initialize the language code variable
$lc = "";
// Check to see that the global language server variable isset()
// If it is set, we cut the first two characters from that string
if(isset($_SERVER['HTTP_ACCEPT_LANGUAGE']))
$lc = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
// Now we simply evaluate that variable to detect specific languages
if($lc == "fr"){
header("location: index_french.php");
exit();
} else if($lc == "de"){
header("location: index_german.php");
exit();
}
else{ // don't forget the default case if $lc is empty
header("location: index_english.php");
exit();
}
?>
This did the job perfectly! I only had a problem left. There was no way to change language, even with direct links into another language because as soon as the page was loading, the php block would redirect me to the borwser's language. This can be a problem if you are living in another country and have for instance Swedish as a mother language but you have your browser in English because you bought your computer in the UK.
So my solution for this issue was to create folders with a duplicate version for every language (even the one for the main language) without this php code on the index.html (and therefore not index.php). So now my website is auto detecting the language and the user also has the option to change it manually in case of they want!
Hope it will help out someone else with the same problem!
I think your idea is great. May be help you shortest code:
$lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
header("location: ".$lang."/index.php");
That should work fine. You could also use http_negotiate_language and discusses here
Most useful this code
$lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
if(file_exists('system/lang/'.$lang.'.php'))
{
include('system/lang/'.$lang.'.php');
}else{
include('system/lang/en.php'); //set default lang here if not exists translated language in ur system
}

multilanguage site with sub folder

Please help me with php file that must redirect to correct language.
the site architecture is
site.com/en
site.com/fr
my cod:
<?php
$sites = array(
"en" => "/en/index",
);
$lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
if (!in_array($lang, array_keys($sites))){
$lang = 'en';
}
// перенаправление на субдомен
header('Location: ' . $sites[$lang]);
?>
You could to append the $_SERVER['PHP_SELF'] variable, that contains the path relative to the document root, to your language folder.
If your path were site.com/fr/file, this variable would contain /fr/file. When you remove the first part of this part, you get the 'language-independent' path of the called script, that you can append to the desired language directory.
If your path is as you described, you could try the following solution (untested!):
<?php
$sites = array(
"en" => "/en",
);
$lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
if (!in_array($lang, array_keys($sites))){
$lang = 'en';
}
$path_to_script = substr($_SERVER['PHP_SELF'], 3);
header('Location: ' . $sites[$lang] . $path_to_script);
?>
EDIT: to clarify the approach:
If the site is site.com/fr/123/index.php, the variable $path_to_script will then contain /123/index.php, the script directory without the leading language dir.
You can then append this to the desired language dir and get the path you wanted: /en/123/index.php
/en/index should be /en/index.php except if you are using Apache's mod_rewrite (not by default). Please provide more details of what is not working so we can help you more.
EDIT:
Furthermore, you could give the user the option of choosing language as 'HTTP_ACCEPT_LANGUAGE' might not be set. In that case, the only choice would be English, which would limit your public.
Some people even recommend about geolocalization, but I find it good enough to add a little drop down menu with languages.

multi-language .htaccess redirect to subdomain

I have a multilanguage website (spanish, english, french) in PHP which main's language is english.
If $_SESSION['idm'] is set to 'en' it loads a file with the translations.
I want to set it up this way:
if the user language is spanish
www.mydomain.com and mydomain.com -> es.mydomain.com
www.mydomain.com/video.php?id=3 -> es.mydomain.com/video.php?id=3
if user language is french
www.mydomain.com and mydomain.com -> fr.mydomain.com
www.mydomain.com/video.php?id=3 -> fr.mydomain.com/video.php?id=3
if not any of the above
www.mydomain.com and mydomain.com -> en.mydomain.com
www.mydomain.com/video.php?id=3 -> en.mydomain.com/video.php?id=3
How do I do that, and, is this good SEO wise?
in PHP:
// check if the current domain is the generic one
$req_domain = $_SERVER['SERVER_NAME'];
if ($req_domain == 'www.mydomain.com' || $req_domain == 'mydomain.com') {
$subdomains = array ('fr' => 'fr.mydomain.com',
'es' => 'es.mydomain.com',
'en' => 'en.mydomain.com');
// get the language from the session variable (if set), or use default
$lang = 'en'; // default language
if ( isset($_SESSION['idm']) && isset($subdomains[$_SESSION['idm']]) )
$lang = $_SESSION['idm']; // selected language
// redirect while maintaining the complete request URI
header('Location: http://' . $domains[$lang] . $_SERVER['REQUEST_URI']);
exit;
}
It's better for SEO than your current session based method which hides the language variations from the search engines.
One slight alteration would be to keep the default language (en) on the main domain.
To make it work best:
Ensure on page links are relative so you don't cause redirects on every click.
Add hreflang meta data to the pages to indicate where the translations are.
Don't force people into a language. Make sure they can easily change.

Categories