PHP changing language version

后端 未结 4 336
走了就别回头了
走了就别回头了 2021-01-16 13:51

I have a website which i want to create other language version. I don\'t want to create folder for each language. I was wondering it it\'s possible to add a combobox on each

4条回答
  •  悲哀的现实
    2021-01-16 14:37

    If you have a combobox, when the user submits it, store the language in the session (session_start(); has to be called) with $_SESSION['lang'] = $_POST['lang'];. I'd advise you to whitelist languages as such:

    session_start();
    
    // define language whitelist
    $allowedLangs = array('en', 'de');
    
    // only store the new user language if it's an allowed one
    if (isset($_POST['lang']) && in_array($_POST['lang'], $allowedLangs)) {
        $_SESSION['lang'] = $_POST['lang'];
    }
    
    // define the user language based on session data or use 'en' as default if not available
    $userLang = isset($_SESSION['lang']) ? $_SESSION['lang'] : 'en';
    
    // parse some language file according to the language
    $translations = // TODO load some file with $userLang here
    

    Of course you should adjust this to your own project and environment. For translation files, you can use a plain PHP file that returns an array like such:

     'Translation',
    );
    

    Then if you include that file, the return value of the include will be the array, so in the above code you could do:

    $translations = include 'translations/'.$userLang.'.php';
    

    You then have to output all your text through this $translations variable, like echo $translations['some.key'].

提交回复
热议问题