Jump to content

[SOLVED] Redirect based browser language + permission to change language


Marco Ro
 Share

Recommended Posts

I am looking in the forum for a solution but I didn't find it.

I redirect people based on their browser language, with I use this code (that I grab somewhere in the forum):

foreach($languages as $language) {
  if(strpos($config->httpHost, "$language->site.it") === 0) {
	$user->language = $language;
	break;
  }
}

$name = $sanitizer->pageName(substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2));;
$language = $languages->get($name);

if($language->id && $name != $user->language->name) {
	$url = "https://www.site.it" . $page->localUrl($language);
	$session->redirect($url);
}

Now the problem is that: the users can't change the language because they are always redirected to theirs browser language.
I would like to let the users change the language. I try to work around Session class, I thought of enabling redirection only on first arrival, but I don't know how to do it.
Maybe I have to work with the cookies? I'm not sure about what I can do.

I find this post, but I will not use this module but incorporate within my _func.php file, because before to get to the language selection I have other statements.

If I have understand well he used this part to make the redirect only in first session, but I'm not sure how can I integrate this  

// Set some session variables then redirect
$this->session->languageAlreadyDetected = true;
if (wire('user')->language->name != $matchedLanguage AND !isset(wire('input')->get->{$this->noDetectGetParam})) {
  $this->session->redirect($page->localUrl($matchedLanguage), false);
}

 

MY SOLUTION:
probably not the best solution, but it works

// set the cookie expire after 5 min, I know is not the best because after 5 min the user not load page is forced to change language, 
// but the average time of a session is that and in this way I'm sure if the user cameback there isn't this cookie  
$user_is_first_timer = !isset( $_COOKIE["FirstTimer"] );
setcookie( "FirstTimer", 1, time() + (60 * 5) );

if( $user_is_first_timer ){

	foreach($languages as $language) {
	if(strpos($config->httpHost, "$language->playwood.it") === 0) {
		$user->language = $language;
		break;
	  }
	}
	$name = $sanitizer->pageName(substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2));;
	$language = $languages->get($name);
	if($language->id && $name != $user->language->name) {
	$url = "https://www.site.com" . $page->localUrl($language);
	$session->redirect($url);
}

 

  • Like 1
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...