2

I want to save the language in a session using $_GET[''] method:

<a href="?lang=fr">French</a>
<a href="?lang=en">English</a>

By default the site language is in french. the site language will be changed if the user choose one from the links above. and then even thought the $_GET['lang'] is not set, i want the $_SESSION['lang'] always saves the last language choosen by the user.

I tried this but its not logic, i know..

$languages = array('en', 'fr');
if(isset($_GET['lang']) AND in_array($_GET['lang'], $languages)){
    $_SESSION['lang'] = $_GET['lang'];
}else{    
    $_SESSION['lang'] = "fr";    
}
require_once('languages/'.$_SESSION['lang'].'.php');

what should I do then to save the last language is session variable?

2
  • make sure you have session_start() Commented Jun 25, 2015 at 18:03
  • Its already there, The problem is when the $_GET['lang'] is set, the language changes, but when the user goes to another page, $_SESSION['lang'] equals "fr", the default language because i made the condition to change the language if the $_GET['lan'] issset and I don't want that, I want the $_SESSION['lang'] always keeps its last value and i justs didn't know the logic there Commented Jun 25, 2015 at 18:07

1 Answer 1

4

What happens is when you don't have the language in url, it sets it back to french.

To fix this you set the language in session if it is given in url, otherwise if session is not set at all, you go by default, which is french.

$languages = array('en', 'fr');
if(isset($_GET['lang']) AND in_array($_GET['lang'], $languages)){
    $_SESSION['lang'] = $_GET['lang'];
}
if(!isset($_SESSION['lang']){    
    $_SESSION['lang'] = "fr";    
}
require_once('languages/'.$_SESSION['lang'].'.php');
Sign up to request clarification or add additional context in comments.

2 Comments

Sidenote: since there's an if, if(!isset($_SESSION['lang']){ $_SESSION['lang'] = "fr"; } could be changed to just else { $_SESSION['lang'] = "fr"; }.
@Fred-ii- Then when user navigates to other pages and language is not set in URL, it will go back to french instead of keeping last languages selected.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.