Note that there are some explanatory texts on larger screens.

plurals
  1. POPHP or htaccess rewrite URL by Accept-Language?
    text
    copied!<p>I've my site set up so I just need to add "?lang=en" or "?lang=es" to change languages English / Spanish.</p> <p>When I enter the site with, for ex, "http://domain.com/something/something_else?lang=es", a cookie is set so I continue to navigate the site in that language.</p> <p>I would like to redirect my users first by the "Accept-Language" value of their browser, but then allow them to continue to navigate the site in other language if they want to.</p> <p>What would be the best way to do it? Would .htaccess work along with the cookie that's set when the language is chosen?</p> <p>EDIT: Here's my updated code with Paul answer:</p> <p>EDIT2: Oh, I just have "en" and "es" languages. I'm not sure on how this code wpuld choose only between this two or set the default... :/</p> <pre><code> if (isset($_GET["lang"])) $this-&gt;setLanguage($_GET["lang"]); elseif (isset($_COOKIE["language"])) $this-&gt;setLanguage($_COOKIE["language"]); elseif (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { // Parse the Accept-Language according to: // http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4 preg_match_all( '/([a-z]{1,8})' . // First part of language e.g en '(-[a-z]{1,8})*\s*' . // other parts of language e.g -us // Optional quality factor '(;\s*q\s*=\s*((1(\.0{0,3}))|(0(\.[0-9]{0,3}))))?/i', $_SERVER['HTTP_ACCEPT_LANGUAGE'], $langParse); $langs = $langParse[1]; $quals = $langParse[4]; $numLanguages = count($langs); $langArr = array(); for ($num = 0; $num &lt; $numLanguages; $num++) { $newLang = strtoupper($langs[$num]); $newQual = isset($quals[$num]) ? (empty($quals[$num]) ? 1.0 : floatval($quals[$num])) : 0.0; // Choose whether to upgrade or set the quality factor for the // primary language. $langArr[$newLang] = (isset($langArr[$newLang])) ? max($langArr[$newLang], $newQual) : $newQual; } // sort list based on value arsort($langArr, SORT_NUMERIC); $acceptedLanguages = array_keys($langArr); $preferredLanguage = reset($acceptedLanguages); $this-&gt;setLanguage($preferredLanguage); } else $this-&gt;setLanguage("en"); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload