I'm trying to create an URL-router, where the website language is defined by the first two chars in the domain. Example: domain.com/en
(the site will then display content in english).
The script below is what I've come up with so far. Focus is at functionality, instead of SEO. However I would like it to be optimized for both, and honestly I'm no expert at search engine optimization.
- Would Googlebot be able to index both the English and Danish content? (notice the way I get the visitors language, and make redirects accordingly)
- Is there anything I could do to improve the script functionality, including SEO handling?
All suggestions for improvement is more than welcome..
class Router {
private $allowedLang = array('da', 'en');
private $langRouter = array(
'en' => 'en_US',
'da' => 'da_DK'
);
function __construct() {
$locale = in_array($_GET['locale'], $this->allowedLang);
if ($locale) {
// If get-var locale is allowed, set it as session
$_SESSION['language'] = $_GET['locale'];
}
if (empty($_SESSION['language'])) {
// If session isn't set, use visitor's browser language
$_SESSION['language'] = $this->getLanguage();
}
// Only redirect if get-var locale is empty or isn't allowed, and target file is not located in lib folder (ajax files etc.)
if ((empty($_GET['locale']) || !$locale) && substr($_SERVER['SCRIPT_NAME'], 0, 4) != '/lib') {
header('Location: /'.$_SESSION['language']);
}
$this->setLanguage($_SESSION['language']);
}
public function setLanguage($lang) {
// If $lang is allowed use it, else default to DEFAULT_LANGUAGE
$locale = (in_array($lang, $this->allowedLang) ? $this->langRouter[$lang] : DEFAULT_LANGUAGE);
// Initiate gettext
putenv("LC_ALL=$locale");
setlocale(LC_ALL, $locale);
bindtextdomain("messages", CLIENT_PATH."/lib/locale");
textdomain("messages");
}
/**
* Get the visitor's language based on browser settings.
* If language isn't found or isn't allowed, default to DEFAULT_LANGUAGE
*/
private function getLanguage() {
if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
$langs = explode(',',$_SERVER['HTTP_ACCEPT_LANGUAGE']);
foreach ($langs as $value) {
$choice = substr($value, 0, 2);
if (in_array($choice, $this->allowedLang)) {
return $choice;
}
}
}
return DEFAULT_LANGUAGE;
}
}