Auto detect language and redirect user

后端 未结 5 1500
孤街浪徒
孤街浪徒 2020-12-13 21:05

I am doing my own website and I managed to write some code that makes directs user to the language version according to the browser\'s language. Here is the script:

5条回答
  •  醉话见心
    2020-12-13 21:44

    PHP 5.3.0+ comes with locale_accept_from_http() which gets the preferred language from the Accept-Language header.

    You should always prefer this method to a self-written method as the header field is more complicated than one might think. (It's a list of weighted preferences.)

    You should retrieve the language like this:

    $lang = locale_accept_from_http($_SERVER['HTTP_ACCEPT_LANGUAGE']);

    But even then, you won't just have en for every English user and es for Spanish ones. It can become much more difficult than that, and things like es-ES and es-US are standard.

    This means you should iterate over a list of regular expressions that you try and determine the page language that way. See PHP-I18N for an example.

提交回复
热议问题