Attaching Browser Information to a Symfony2 Request Object

PHP has a function to get the visitors browser information. It will return a
lot of information and you can read more about it at
[php.net/get_browser](http://php.net/get_browser). In this example I will show
you how to set this up in your symfony2 project without the need to edit your
php.ini file.

First you need to install
[garetjax/phpbrowscap](https://github.com/GaretJax/phpbrowscap)

{% highlight bash %}
php composer.phar require garetjax/phpbrowscap:dev-master
{% endhighlight %}

The above command will install the code needed.

Next up, we want to hook into the `kernel.request` event so we can add some
extra information.

{% highlight php %}
container = $container;
}

/**
* @param GetResponseEvent $event
*/
public function onKernelRequest(GetResponseEvent $event)
{
$bc = new Browscap($this->container->getParameter(‘kernel.cache_dir’));
$event->getRequest()->attributes->set(‘_browser’, $bc->getBrowser());
}
}
{% endhighlight %}

Now for the services.xml file

{% highlight xml %}








{% endhighlight %}

That’s all the code that is required. Now let’s look at an example of how to
get the information from the controller.

{% highlight php %}
getRequest()->attributes->get(‘_browser’);
die(var_dump($browser));
}
}
{% endhighlight %}

![](http://media.tumblr.com/tumblr_majri33WLS1rtbdeo.png)

Here’s what it looks like in the profiler.

![](http://media.tumblr.com/tumblr_majrkr2YaH1rtbdeo.png)

### References and Resources

* https://github.com/GaretJax/phpbrowscap/wiki/QuickStart
* http://php.net/get_browser
* http://symfony.com/doc/master/book/internals.html#kernel-request-event
* http://symfony.com/doc/master/reference/dic_tags.html#kernel-event-listener