Browser-Language detection

Gets the ”accepted languages”-string from the browser and finds the best fitting from the available languages defined in $langs. Result is stored in $lang.

<?php
 
  $langs = array('de', 'en');
  if (!empty($_GET['lang']) && in_array($_GET['lang'], $langs)) {
    $lang = $_GET['lang'];
  } else {
    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];
    }
  }
 
?>

The following code detects the language and tries to find a file language_pagename.php to load.

languagedetection.inc.php
<?php
 
  if ( !empty($_GET['lang']) && file_exists( BASE_DIR_LOCAL . 'includes/languages/' . $_GET['lang'] . '.php') ) {
    $LANG_INCLUDE = $_GET['lang'];
  } elseif ( empty($_SESSION['LANG_INCLUDE']) ) {
    if (!empty($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
      $browserlang = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
      $langs = getLanguages();
      $li = 999;
      $LANG_INCLUDE = LANGUAGE_FALLBACK;
      if ($langs !== false) {
        foreach ($langs as $l) {
          $x = strpos($browserlang, $l);
          if ($x !== false && $x<$li) {
            $li = $x;
            $LANG_INCLUDE = $l;
          }
        }
      }
    } else {
      $LANG_INCLUDE = LANGUAGE_FALLBACK;
    }
  } elseif ( !empty($_SESSION['LANG_INCLUDE']) ) {
    $LANG_INCLUDE = $_SESSION['LANG_INCLUDE'];
  }
  if (defined('SESSIONS')) { $_SESSION['LANG_INCLUDE'] = $LANG_INCLUDE; }
 
  require( BASE_DIR_LOCAL . 'includes/languages/' . $LANG_INCLUDE . '.php');   // Load common phrases
 
 
  if ( BASE_DIR != '/' ) {
    $callingfile = str_replace( BASE_DIR, '', $_SERVER['PHP_SELF'] ); // Extract calling file path relative to BASE_DIR
  } else {
    $callingfile = $_SERVER['PHP_SELF'];
  }
  if (strrpos($callingfile, '/')!==false) {
    $callpath = substr($callingfile, 0, strrpos($callingfile, '/')+1);
    $callfile = substr($callingfile, strrpos($callingfile, '/')+1);
  } else {
    $callpath = '';
    $callfile = $callingfile;
  }
  $spfile = BASE_DIR_LOCAL . 'includes/languages/' . $callpath . $LANG_INCLUDE . '_' . $callfile;
  if ( file_exists( $spfile ) ) {
    require($spfile);  // Load page specific phrases, if there are some
  }
 
  function getBeats($curtime = -1) {
    if ($curtime < 0) {
      list($usec, $sec) = explode(" ", microtime());
      $curtime = ((float)$usec + (float)$sec);
    }
    $utcdiff = date('Z', $curtime);
    $utctime = $curtime - $utcdiff;
    $bmttime = $utctime + 3600;
    $ssm = date('H', $bmttime)*3600 + date('i', $bmttime)*60 + date('s', $bmttime);
    $ibeats  = $ssm/86.4;
    return '<ABBR title="swatch Internet time (' . date(DATE_FORMAT, $bmttime) . ')">' . sprintf('@%06.2f', $ibeats) . '</ABBR>';
  }
 
  function titleLine() {
    // Title line with page title, server time and language selector
    echo "<TABLE BORDER=0 WIDTH=100%><TR><TD ALIGN=\"left\" VALIGN=\"top\">";
    if (defined('PAGE_HEADING')) {
      echo "<SPAN CLASS=\"pagehead\">" . PAGE_HEADING . "</SPAN>";
    }
    echo "</TD><TD ALIGN=\"right\" VALIGN=\"top\"><SPAN CLASS=\"datetime\">" . HEAD_SERVERTIME . " ";
    echo strftime(DATE_TIME_FORMAT) . ' ' . getBeats() . "</SPAN>&nbsp;";
    print_language_selector();
    echo "</TD></TR></TABLE>\r\n";
  }
 
  function getLanguages() {
    $dir = dir( BASE_DIR_LOCAL . 'includes/languages/');
    if ($dir) {
      while ($file = $dir->read()) {
        if (substr($file, strrpos($file, '.')) == '.php' && strpos($file, '_') === false) {
          $langname = substr($file, 0, strrpos($file, '.'));
          $languages[] = $langname;
        }
      }
      $dir->close();
      return $languages;
    } else {
      return false;
    }
  }
 
  function print_language_selector() {
    $langs = getLanguages();
    if ($langs !== false) {
      foreach ($langs as $langname) {
        if ($langname != LANGUAGE_CODE) {
          echo '<A HREF="?lang=' . $langname . '"><IMG SRC="' . BASE_DIR . 'includes/languages/' . $langname . '_trans.png" BORDER=0 WIDTH=24 HEIGHT=15 TITLE="' . $langname . '"></A>';
        } else {
          echo '<IMG SRC="' . BASE_DIR . 'includes/languages/' . $langname . '.gif" BORDER=0 WIDTH=24 HEIGHT=15 TITLE="' . LANGUAGE_NAME . ' ' . HEAD_LANGUAGE_IS_CHOSEN . '!">';
        }
        echo '&nbsp;';
      }
    } else {
      echo PAGE_NOLANGUAGES;
    }
  }
 
?>

 
snippets/php/languagedetection.txt · Last modified: 2010-01-15 14:42.10 by mbirth
 
Except where otherwise noted, content on this wiki is licensed under the following license:CC Attribution-Noncommercial-Share Alike 3.0 Unported
Recent changes RSS feed Donate Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki Contents powered by Club-Mate Contents powered by BassDrive.com Labelled with ICRA