Last active
April 13, 2018 12:42
-
-
Save w-jerome/fc25013c492c0b49bbcde55d4c1e2c76 to your computer and use it in GitHub Desktop.
PHP — Url lang redirection
This file contains hidden or 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 | |
| // On check d'abord si on a déjà était "routé" par le système de langue en "fr" ou "en" (ou les langues disponible) | |
| $url = trim($_SERVER['REQUEST_URI'], "/"); | |
| // On définis les langues possibles | |
| $langList = ["fr", "en"]; | |
| // On prépare le regex qui va vérifier si l'url contient le "routage" par la langue | |
| $langRegex = ""; | |
| $langRegex1 = array_map(function($value) { return "$value$"; }, $langList); | |
| $langRegex2 = array_map(function($value) { return "$value\/"; }, $langList); | |
| $langRegex = array_merge($langRegex1, $langRegex2); | |
| $langRegex = implode("|", $langRegex); | |
| preg_match("/^($langRegex)/", $url, $matchLang); // "/^(fr$|en$|fr\/|en\/)/" | |
| if ($matchLang && isset($matchLang[0])) { | |
| // Si c'est le cas on assign la langue selon celle qui est passé | |
| $lang = trim($matchLang[0], "/"); | |
| } else { | |
| // Sinon on cherche la langue accepté par le naviguateur (on check la langue et fait la redirection plus tard) | |
| $lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2); | |
| } | |
| if (!in_array($lang, $langList)) { | |
| // Si la langue détecté plus haut n'est pas dans la liste, on attribut une langue par défaut | |
| $lang = "en"; | |
| } | |
| // Si on a pas encore était "routé", alors on redirige vers la langue choisis ou celle attribuée par défaut en passant le reste de l'url | |
| if (!$matchLang || !isset($matchLang[0])) { | |
| $protocol = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') ? "https" : "http"; // On check si on est en https | |
| $urlRedirect = "$protocol://{$_SERVER["HTTP_HOST"]}/$lang"; // On crée le lien avec la langue | |
| $urlRedirect .= $_SERVER['REQUEST_URI']; // On ajoute le reste l'url | |
| header("Location: $urlRedirect"); | |
| exit; | |
| } | |
| var_dump($lang); | |
| exit; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment