cancel
Showing results for 
Search instead for 
Did you mean: 

How to automatically redirect to a store view based on the browser language

How to automatically redirect to a store view based on the browser language

I'm trying to automatically redirect people to a store view based on their browser language.

Situation: 5 store views (en, de, it, fr, nl) Magento 1.9.1

I used this piece of code in index.php:

 

require_once 'app/Mage.php';
/* Determine correct language store based on browser */
function getStoreForLanguage()
{
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 $stores[$lang];
    }
}
return Mage::app()->getStore();
}
/* Auto redirect to language store view if request is for root */
if ($_SERVER['REQUEST_URI'] === '/') {    header('Location: '.getStoreForLanguage()->getBaseUrl());
    exit;
}

#Varien_Profiler::enable();

#Mage::setIsDeveloperMode(true);

#ini_set('display_errors', 1);umask(0);
Mage::run(); 

 

It seems like the browser wants to redirect because if i type in: domain.com it goes for a second to domain.com/nl but after a second an error appears:

"There has been an error processing your request. Exception printing is disabled by default for security reasons."

If i look at the error in the log file i see this:

 

a:4:{i:0;s:53:"Mage registry key "application_params" already exists";i:1;s:349:"#0 /var/www/webroot/ROOT/app/Mage.php(223): Mage::throwException('Mage registry k...')
#1 /var/www/webroot/ROOT/app/code/core/Mage/Core/Model/App.php(338): Mage::register('application_par...', Array)
#2 /var/www/webroot/ROOT/app/Mage.php(684): Mage_Core_Model_App->run(Array)
#3 /var/www/webroot/ROOT/index.php(129): Mage::run('', 'store')
#4 {main}";s:3:"url";s:4:"/nl/";s:11:"script_name";s:10:"/index.php";}
7 REPLIES 7

Re: How to automatically redirect to a store view based on the browser language

Is that the entire index.php?

Problem solved? Click Accept as Solution!
www.iwebsolutions.co.uk | Magento Small Business Partner

Re: How to automatically redirect to a store view based on the browser language

No the entire index.php without the previous code for redirecting looks like this:

 

<?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.3.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.3.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
 */
define('MAGENTO_ROOT', getcwd());

$compilerConfig = MAGENTO_ROOT . '/includes/config.php';
if (file_exists($compilerConfig)) {
    include $compilerConfig;
}

$mageFilename = MAGENTO_ROOT . '/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);

/* Store or website code */
$mageRunCode = isset($_SERVER['MAGE_RUN_CODE']) ? $_SERVER['MAGE_RUN_CODE'] : '';

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

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

Thanks for your quick response!

Re: How to automatically redirect to a store view based on the browser language

No worries Smiley Happy

Can you post your entire index.php WITH your modifications in. It looks like it is running the mage app twice.

Problem solved? Click Accept as Solution!
www.iwebsolutions.co.uk | Magento Small Business Partner

Re: How to automatically redirect to a store view based on the browser language

<?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.3.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.3.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;
}

require_once 'app/Mage.php';
/* Determine correct language store based on browser */
function getStoreForLanguage()
{
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 $stores[$lang];
    }
}
return Mage::app()->getStore();
}
/* Auto redirect to language store view if request is for root */
if ($_SERVER['REQUEST_URI'] === '/') {    header('Location: '.getStoreForLanguage()->getBaseUrl());
    exit;
}

#Varien_Profiler::enable();

#Mage::setIsDeveloperMode(true);

#ini_set('display_errors', 1);umask(0);
Mage::run(); 


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

/**
 * Compilation includes configuration file
 */
define('MAGENTO_ROOT', getcwd());

$compilerConfig = MAGENTO_ROOT . '/includes/config.php';
if (file_exists($compilerConfig)) {
    include $compilerConfig;
}

$mageFilename = MAGENTO_ROOT . '/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);

/* Store or website code */
$mageRunCode = isset($_SERVER['MAGE_RUN_CODE']) ? $_SERVER['MAGE_RUN_CODE'] : '';

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

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

Re: How to automatically redirect to a store view based on the browser language

Get rid of the following from half way down your file

 

Mage::run();

 I would also actually remove 

 

require_once 'app/Mage.php';

 from the top of the file and then move your if check to underneath

 

require_once $mageFilename;

 

Problem solved? Click Accept as Solution!
www.iwebsolutions.co.uk | Magento Small Business Partner

Re: How to automatically redirect to a store view based on the browser language

Well i'm not getting any errors anymore Smiley Happy So that's a start haha

But problem is now that i'm not getting sent to the right store view based on browser language. Just goes to the default store view Smiley Sad

Re: How to automatically redirect to a store view based on the browser language

To be perfectly honest this is not how i would have done this. Instead i would have set up a module with an observer that checked the url. The main issue i can see though here is that in your function you have nothing that populares the $stores var, if it even gets that far.

 

Debugging by yourself required Smiley Happy

Problem solved? Click Accept as Solution!
www.iwebsolutions.co.uk | Magento Small Business Partner