Skip to content

Instantly share code, notes, and snippets.

@esolitos
Created December 4, 2014 23:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save esolitos/6b98beb2658bc3cd917e to your computer and use it in GitHub Desktop.
Save esolitos/6b98beb2658bc3cd917e to your computer and use it in GitHub Desktop.
Language redirect in php with javascript fallback.
<?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&hellip;</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