Browser language detection with enabled page cache

Public

Due to a core bug language detection isn't working when the page cache is enabled

Get raw version
php
  1. function HOOK_boot() {
  2. global $user;
  3. $request_uri = request_uri(); // Get URI cross platform.
  4. $parsed_url = parse_url($request_uri); // Separate path from query string.
  5. //echo $parsed_url;
  6. // If the user is anonymous and the requested path equals Drupal's base path (= frontpage without language prefix).
  7. if (empty($user->uid) && $parsed_url['path'] === $GLOBALS['base_path']) {
  8. // Get enabled languages.
  9. require_once DRUPAL_ROOT . '/includes/locale.inc';
  10. $enabled_languages = language_list('enabled');
  11.  
  12. // Get the browser's preferred language (langcode) or false on failure.
  13. $langcode_from_browser = locale_language_from_browser($enabled_languages[1]);
  14.  
  15. // If the browser's preferred language is found and it differs from the site's default langcode.
  16. if ($langcode_from_browser && $langcode_from_browser !== language_default()->language) {
  17. // Redirect the user to a language prefixed URL.
  18. header('Vary: Accept-language', false);
  19. header('Content-Language: ' . $langcode_from_browser);
  20. header('Location: /' . $langcode_from_browser . $request_uri, true, 302);
  21. exit;
  22. }
  23. }
  24. }

Comments

Manu b.'s picture

Hi,
It would be great if you could link to the d.o. bug, so we could know if its still valid.

Thanks!