Snippets

Create an account or login to be able to add, comment and rate snippets.

Navigation

Set user culture from domain name

This filter tries to set the user culture by reading the domain part of the url. I use it for SEO, giving a different domain for each lang of my site.

Add this to your settings.yml :

    domain_culture:
       fr:   [.net, .fr, fr.mydomain.info]
       it:   [it.mydomain.info]
       en:   [.co.uk, .com, .mydomain.info]
 

Order is important : first match will assign the corresponding culture.

Create a lib/filters/domainCultureFilter.class.php file :

<?php
 
class domainCultureFilter extends sfFilter
{
    public function execute($filterChain)
    {
        $user = $this->getContext()->getUser();
        $request = $this->getContext()->getRequest();
        if (!$request->getParameter('sf_culture'))
        {
            if ($user->getAttribute('first_request', true))
            {
                $user->setAttribute('first_request', false);
                $domainCulture=sfConfig::get('sf_domain_culture');
                foreach ((array)$domainCulture as $culture=>$domains)
                {
                    foreach ((array)$domains as $domain)
                    {
                        $pattern = '/'.$domain.'/';
                        if (preg_match( $pattern ,  $_SERVER['HTTP_HOST']) )
                        {
                            $user->setCulture($culture);
                        }
                        break 2;
                    }
                }
            }
        }
        // Execute next filter
        $filterChain->execute();
    }
}
 

Add the filter to filters.yml :

# insert your own filters here
culture:
   class: domainCultureFilter
 

Comments are very welcome.

by Pierre Bastoul on 2009-04-10, tagged culture  domain  filter 

Comments on this snippet

gravatar icon
#1 Anton Stoychev on 2009-05-01 at 04:04

Neat snippet but to be paranoid you can set the regular expression to :[code php] $pattern = '/'.$domain.'$/';

$request->getHost();

Cheers for the snippet!

gravatar icon
#2 Guillaume Moigneu on 2009-05-02 at 11:32

The "break 2" command should be inside the preg_match if.

if (preg_match( $pattern , $_SERVER['HTTP_HOST']) ) { $user->setCulture($culture); break 2; }

gravatar icon
#3 Andrzej Skiba on 2009-05-31 at 09:40

Thanks for this great snippet! Since I'm new to Symfony I had no idea how to go about doing this.

You need to create an account or log in to post a comment or rate this snippet.