Detect Browser Language in PHP

后端 未结 13 1444
孤城傲影
孤城傲影 2020-11-22 09:16

I use the following PHP script as index for my website.

This script should include a specific page depending on the browser\'s language (automatically detected).

13条回答
  •  再見小時候
    2020-11-22 09:38

    Unfortunately, none of the answers to this question takes into account some valid HTTP_ACCEPT_LANGUAGE such as:

    • q=0.8,en-US;q=0.5,en;q=0.3: having the q priority value at first place.
    • ZH-CN: old browsers that capitalise (wrongly) the whole langcode.
    • *: that basically say "serve whatever language you have".

    After a comprehensive test with thousands of different Accept-Languages in my server, I ended up having this language detection method:

    define('SUPPORTED_LANGUAGES', ['en', 'es']);
    
    function detect_language() {
        foreach (preg_split('/[;,]/', $_SERVER['HTTP_ACCEPT_LANGUAGE']) as $sub) {
            if (substr($sub, 0, 2) == 'q=') continue;
            if (strpos($sub, '-') !== false) $sub = explode('-', $sub)[0];
            if (in_array(strtolower($sub), SUPPORTED_LANGUAGES)) return $sub;
        }
        return 'en';
    }
    

提交回复
热议问题