简体   繁体   中英

Using accept language header to guess user's country, if available

I want to use Javascript/PHP to determine if a user's browser has a country (locale variant) defined in the accept-language header.

Knowing that the contents of the accept-language header value can vary, and is not always accurate, is there a way to logically determine if a country present in the accept-language header string? And then extract that via JS?

For example, if a user's accept language header contains en-US, I would want to set a local variable="US".

My intial thought was to create a very large array of all accept header language and locale values and check against that, but that did not seem like a very efficient approach.

The Accept-Language header has a couple of formats it can take, see the documentation on MDN . Getting the preferred languages as a structured list (like an array sorted by q-factor) is just a matter of parsing that list in a way that is resilient to all the possible permutations of the header values.

Instead of trying to write this logic yourself, it's simpler to use a library built for this exact purpose, which will be better at handling all kinds of weird edge-cases. For example, willdurand/Negotiation allows you to parse the Accept-Language header and match it to a list of locales supported by your site to find the best language to use.

You will have to do this on the server-side (in PHP). Once you know the language, you can pass that to client-side JavaScript in a number of ways. For example, you can use the JS tag to include a piece of JavaScript in your page template that sets a global variable with the determined language.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM