Created
June 21, 2012 16:12
-
-
Save daigofuji/2966774 to your computer and use it in GitHub Desktop.
PHP LANGUAGE DETECTION
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 | |
/* | |
PHP LANGUAGE DETECTION SCRIPT | |
written by Mischa Szeker (www.szeker.ch) | |
January 21, 2011 | |
http://www.szeker.net/2011/02/10/php-language-detection-script/ | |
*/ | |
/* Setting variables */ | |
$langs = array('en', 'de'); | |
$cookie_name = "lang_cookie"; | |
$cookie_domain = ".yourdomain.com"; | |
if (!empty($_GET['lang']) && in_array($_GET['lang'], $langs)) { | |
/* Set language */ | |
$lang = $_GET['lang']; | |
/* Set cookie */ | |
$set_cookie = true; | |
} else { | |
/* Check if cookie exists */ | |
if ( isset($_COOKIE[$cookie_name]) AND !empty($_COOKIE[$cookie_name]) AND in_array($_COOKIE[$cookie_name], $langs) ) { | |
/* Get cookie and set language*/ | |
$lang = $_COOKIE[$cookie_name]; | |
} else { | |
/* Get browser language */ | |
if (!empty($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { | |
$browserlang = $_SERVER['HTTP_ACCEPT_LANGUAGE']; | |
$li = 999; | |
$lang = $langs[0]; | |
foreach ($langs as $l) { | |
$x = strpos($browserlang, $l); | |
if ($x !== false && $x<$li) { | |
$li = $x; | |
$lang = $l; | |
} | |
} | |
} else { | |
$lang = $langs[0]; | |
} | |
/* Set cookie */ | |
$set_cookie = true; | |
} | |
} | |
/* Debug language output */ | |
//echo $lang; | |
/* Redirect */ | |
header( 'Location: /' .$lang . '/' ) ; | |
/* Finally set cookie */ | |
if ($set_cookie) { setcookie("$cookie_name", $lang, time()+(60*60*24*365), "/", $cookie_domain); } | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment