2

I'm using a session for setting language

if(!isset($GLOBALS['lang'])){
    $GLOBALS['lang'] = 'en';
}

Then I'm using ajax to update this:

var lang = 'no'; 

$.ajax({
    type: "POST",
    url: url,
    data: {
          lang : lang
    },
    success: function (data) { (...) }
});

The file being called looks like this:

global $lang;

if(strlen($_POST['lang']) == 2 ){
    $lang = $_POST['lang'];
    $result = array('lang_set' => $lang);
    echo json_encode($result);
}

But my global session is not changed. I'm guessing this is due to the fact that lang.php uses another session instance.

I'm using Wordpress so I'm looking into if I can use some of the built in functions for this purpose. But I'm wondering if I can use PHP sessions for keeping track of selected language? Or do I have to use another method like adding selected language to my url?

UPDATE
Thanks to Ghost, I made it work. If you are using Wordpress, I'm doing the following in functions.php:

// Initialize session
if(session_id() == '') {
    session_start();
}

// Set lang session with default language
if(!isset($_SESSION['lang'])){
    $_SESSION['lang'] = 'no';
}

//globals
$GLOBALS['lang'] = $_SESSION['lang'];
1
  • 1
    if( !session_id() ){session_start();} Commented Sep 26, 2014 at 15:03

1 Answer 1

3

If you want them to persist on the entire application, use sessions:

session_start();
if(!isset($_SESSION['lang'])){
    $_SESSION['lang'] = 'en';
}

Then on the other:

session_start();

if(strlen($_POST['lang']) == 2 ){
    $_SESSION['lang'] = $_POST['lang'];
    $result = array('lang_set' => $_SESSION['lang']);
    echo json_encode($result);
}
Sign up to request clarification or add additional context in comments.

6 Comments

That will not work (tested) because when you open lang.php, it creates another session instance (I think).
@Steven nope, it will work, you need a session_start() on those scripts where you need to access session variables
Yea, sorry - my bad. I forgot session_start();in my lang.php file. Thanks :)
@Steven anyway, the important thing is its always on top of your php file, and don't call it twice in the same php file.
I only call it twice. Once in lang.php and once in my function.php file - where I place the session in $GLOBALS['lang']
|

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.