Created
December 4, 2014 23:17
-
-
Save esolitos/6b98beb2658bc3cd917e to your computer and use it in GitHub Desktop.
Language redirect in php with javascript fallback.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
if ( isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) && strlen($_SERVER['HTTP_ACCEPT_LANGUAGE']) >= 2 ) | |
{ | |
$allowLang = array('en', 'it', 'de', 'fr'); | |
$base_url = $_SERVER['HTTP_HOST'] . rtrim(dirname($_SERVER['PHP_SELF']), '/\\'); | |
$lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2); | |
if ( !in_array($lang, $allowLang) ) { | |
$lang = 'en'; | |
} | |
header("Location: http://{$base_url}/{$lang}/", TRUE, 303); | |
} | |
?> | |
<html> | |
<head> | |
<meta http-equiv="Content-type" content="text/html; charset=utf-8"> | |
<title>Redirect…</title> | |
<script type="text/javascript"> | |
// Fallback, if php was not able to get a lang, try with javascript! | |
function langRedir() { | |
var allowLang = ['en', 'it', 'de', 'fr']; | |
userLang = navigator.language ? navigator.language : navigator.userLanguage, | |
lang = userLang.split('-')[0], | |
dest = 'en/'; | |
for (var i = allowLang.length - 1; i >= 0; i--) { | |
if( allowLang[i] == lang ) { | |
dest = lang + '/'; | |
} | |
} | |
if ( window.location.replace ) { window.location.replace(dest); } | |
else { window.location=dest; } | |
} | |
</script> | |
</head> | |
<body id="redirect" onload='langRedir()'> | |
<center> | |
<h1>Redirecting to the correct language...</h1> | |
</center> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment