Computers: October 2008 Archives

If you’re doing international (i18n or Iñtërnâtiônàlizætiøn) work (or just want to make your site available in several languages), you’ll likely need to determine the users default language in your PHP code to determine which language to serve up. Searching the web yields one common code piece frequently; unfortunately as you’ll soon see it may not give you the results you need as it ignores parts of the HTTP spec which may or may not be critical to the accuracy of the results.

HTTP Language Headers

The interchange between browser and server transfers information about the client and its capabilities in headers — user agent, what it will accept, and (what we’re interested in) language. The browser sends language information in a header called HTTP_ACCEPT_LANGUAGE, which looks something like this:

 es,en-us;q=0.3,de;q=0.1

Those values state the browser accepts Spanish (es), US English (en-us), and German (de). Obviously, most browsers don’t send so many possibilities, but you get the idea. Most of the code you can find to determine default language simply searches the header for the first 2-letter language code and returns the first it finds. But looking at the example, you’ll note some additional information q=0.3 — what’s that?