Click here to Skip to main content
13,446,015 members (37,022 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as


Posted 8 May 2017

Setting HTTP Headers in Symfony Crawler Client

, 8 May 2017
Rate this:
Please Sign up or sign in to vote.
Setting HTTP Headers in Symfony Crawler Client


I’ve recently created a Symfony application that keeps track of the browser that submitted the form. When developing functional tests for this application, I needed to set the HOST and User-Agent HTTP headers on the client. This article is about how to do that.

Creating the Client

All functional test cases should extend WebTestCase in Symfony as described in the testing documentation. So your class should be written like that and each of your tests should include the word “test” in the function name. So an example might be like so:

// tests/AppBundle/Functional/DefaultControllerTest.php
namespace tests\AppBundle\Functional;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class DefaultControllerTest extends WebTestCase
   public function testLogin(){

Where the above file is created in the tests\AppBundle\Functional folder. Then since the class extends WebTestCase, now we can create a client like so:

$client = static::createClient();

This just creates the default client, but doesn’t set any specific headers.

Setting the Headers

You may need various HTTP headers for your application. In my case, I needed Host and User-Agent headers. The parameters of the test client is described in the API documentation, and essentially parameter 2 is an array that is the equivalent of a PHP $_SERVER. So in my case, I used code like the following:

$client = static::createClient(array(), array(
        'HTTP_HOST' => 'mySymfonyApp', // Set HOST HTTP Header.
        'HTTP_USER_AGENT' => 'Symfony Browser/1.0', // Set Agent header.

Notice in the above code, any header is prefixed with HTTP_, and a dash is replaced with underscore. So then User-Agent becomes: HTTP_USER_AGENT

Now with the above code, it will see the client (User-Agent) as Symfony Browser version 1.0.

Hopefully this helps someone out.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Alvin Bunk
Software Developer Taft College
United States United States
I’m a software developer. Currently I’m working at Taft College as a Student Success and Support Programmer.

You may also be interested in...

Comments and Discussions

-- There are no messages in this forum --
Permalink | Advertise | Privacy | Terms of Use | Mobile
Web04-2016 | 2.8.180314.2 | Last Updated 8 May 2017
Article Copyright 2017 by Alvin Bunk
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid