Browser language auto-detection in Magento

By default, Magento shows the store that has been configured «by default». Adding browser language auto-detection is pretty easy editing the Magento index.php file. We just need to check what’s the user browser main language and then try to load the store that uses that code.

It’s important to note that maybe the user has already selected a preferred language before. In that case, we just check that the variable $_SERVER[‘MAGE_RUN_CODE’] is set.

Make a copy of your old-fashioned index.php file a create a new one with the following code.

  • Note the variable $default_language_code, which sets the default language code when the detected user browser language code doesn’t match with any of our store codes)
  • Note also that this code is compatible with Magento 1.6+ and 1.11+ (you can try using it for older versions, it will probably work).
  • Last but not least, I’ve taken the main getLanguageCode() from the Magento Wiki. I just modified it in order to play with codes instead of stores.
<?php
/**
 * Magento
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Open Software License (OSL 3.0)
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/osl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@magentocommerce.com so we can send you a copy immediately.
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade Magento to newer
 * versions in the future. If you wish to customize Magento for your
 * needs please refer to http://www.magentocommerce.com for more information.
 *
 * @category   Mage
 * @package    Mage
 * @copyright  Copyright (c) 2008 Irubin Consulting Inc. DBA Varien (http://www.varien.com)
 * @license    http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
 */

if (version_compare(phpversion(), '5.2.0', '<')===true) {
    echo  '<div style="font:12px/1.35em arial, helvetica, sans-serif;"><div style="margin:0 0 25px 0; border-bottom:1px solid #ccc;"><h3 style="margin:0; font-size:1.7em; font-weight:normal; text-transform:none; text-align:left; color:#2f2f2f;">Whoops, it looks like you have an invalid PHP version.</h3></div><p>Magento supports PHP 5.2.0 or newer. <a href="http://www.magentocommerce.com/install" target="">Find out</a> how to install</a> Magento using PHP-CGI as a work-around.</p></div>';
    exit;
}

/**
 * Error reporting
 */
error_reporting(E_ALL | E_STRICT);

/**
 * Compilation includes configuration file
 */
$compilerConfig = 'includes/config.php';
if (file_exists($compilerConfig)) {
    include $compilerConfig;
}

$mageFilename = 'app/Mage.php';
$maintenanceFile = 'maintenance.flag';

if (!file_exists($mageFilename)) {
    if (is_dir('downloader')) {
        header("Location: downloader");
    } else {
        echo $mageFilename." was not found";
    }
    exit;
}

if (file_exists($maintenanceFile)) {
    include_once dirname(__FILE__) . '/errors/503.php';
    exit;
}

require_once $mageFilename;

#Varien_Profiler::enable();

if (isset($_SERVER['MAGE_IS_DEVELOPER_MODE'])) {
    Mage::setIsDeveloperMode(true);
}

#ini_set('display_errors', 1);

umask(0);

/* Language detection */

function getLanguageCode()
{
    $default_language_code = 'en';
    if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
        foreach (explode(",", strtolower($_SERVER['HTTP_ACCEPT_LANGUAGE'])) as $accept) {
            if (preg_match("!([a-z-]+)(;q=([0-9.]+))?!", trim($accept), $found)) {
                $langs[] = $found[1];
                $quality[] = (isset($found[3]) ? (float) $found[3] : 1.0);
            }
        }
        // Order the codes by quality
        array_multisort($quality, SORT_NUMERIC, SORT_DESC, $langs);
        // get list of stores and use the store code for the key
        $stores = Mage::app()->getStores(false, true);
        // iterate through languages found in the accept-language header
        foreach ($langs as $lang) {
            $lang = substr($lang,0,2);
            if (isset($stores[$lang]) && $stores[$lang]->getIsActive()) 
                return $lang;
        }
    }
    return $default_language_code;
}

/* Store or website code */
if(isset($_SERVER['MAGE_RUN_CODE']))
    $mageRunCode = $_SERVER['MAGE_RUN_CODE'];
else
    $mageRunCode = getLanguageCode();

/* Run store or run website */
$mageRunType = isset($_SERVER['MAGE_RUN_TYPE']) ? $_SERVER['MAGE_RUN_TYPE'] : 'store';

Mage::run($mageRunCode, $mageRunType);

2 comments

    • Eric on July 24, 2012 at 8:40 am

    Reply

    I’ve tested in 1.7.0.2 version and I get a 404 error.
    I think that the problem es within this code:

    if (isset($stores[$lang]) && $stores[$lang]->getIsActive()) {
    return $lang;
    }

    Never is true the comparison “isset($stores[$lang])”. Any help?

  1. Reply

    Thanks for sharing this tip, works perfectly on our store, magento 1.7

Leave a Reply

Your email address will not be published.