Skip to content

Instantly share code, notes, and snippets.

@arosemena
Last active August 29, 2015 14:02
Show Gist options
  • Save arosemena/57ad4a08c0868a52c02d to your computer and use it in GitHub Desktop.
Save arosemena/57ad4a08c0868a52c02d to your computer and use it in GitHub Desktop.
Simple class to check a client language from the HTTP headers
<?php
class LangCheck
{
private $default;
private $available;
/**
* @param array $available An array containing the available locales
* @param string $default The default language in case none is found
*/
public function __construct($available = ['es'], $default = 'es')
{
$this->default = $default;
$this->available = $available;
}
/**
* @return string Either the language stored on the cookie or Default
*/
private function cookie() {
if(isset($_COOKIE['preferred_language'])) {
$preferred = $_COOKIE['preferred_language'];
if(in_array($preferred, $this->available)) {
return $preferred;
}
}
return "Default";
}
/**
* The header is sent by most of the modern browsers, it looks something
* like this en-US,en;q=0.8,es;q=0.6, I ignore the q value because it's
* implicitly ordered by the browser
*
* @param string $header The HTTP header HTTP_ACCEPT_LANGUAGES from
* the global $_SERVER array
* @return string The 2 letter language identifier
*/
public function get($header = "")
{
$regex = '/([a-zA-Z]{2});/';
$languages = [];
preg_match_all($regex, $header, $languages);
if($this->cookie() != 'Default') {
return $this->cookie();
}
foreach($languages[1] as $language) {
if(in_array($language, $this->available)) {
return $language;
}
}
return $this->default;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment