Headers already sent... what's up PHPUnit?

Here we go with a simple workaround to resolve a bad error that you can encounter with PHPUnit: headers already sent and failure of the tests.

It happens, sometimes, that you have to work with the headers but your tests fail because PHPUnit sends headers before your application, and your session_start() ( or similar ) call produces the error:

headers already sent by (output started at...

So you need to include a session_start() before PHPUnit is executed.

This can be done with the latest releases of PHPUnit ( > 3.3 ) using a bootstrap file.

Talking to *buntu users: installing PHPUnit via package manager (or apt-get) will install the 3.2.x version, not compatible with the bootstrapping stuff we need to do.

You can read an amazing tutorial on installing PHPUnit via pear on *buntu.

So after having succesfully installed PHPUnit ( today the lates package I could retrieve via PEAR was 3.4.9 )… let’s create this ( very silly ) bootstrap:

cd path/to/my/project/test/unit
sudo gedit bootstrap.php

filling the file with a simple:


So now you can lunch your tests using this syntax:

phpunit --bootstrap bootstrap.php MyPhpunitTest(.php)

If you use an XML config file you can use:

phpunit --bootstrap bootstrap.php --configuration phpunit.xml

or, adding this


in the opening tag of the XML ( <phpunit> ), simply this:

phpunit --configuration phpunit.xml

as you normally do.

Hi there! I recently wrote an ebook on web application security, currently sold on leanpub, the Amazon Kindle store and gumroad.

It contains 160+ pages of content dedicated to securing web applications and improving your security awareness when building web apps, with chapters ranging from explaining how to secure HTTP cookies with the right flags to understanding why it is important to consider joining a bug bounty program.

Feel free to skim through some of the free chapters published on this blog and, if the content seems interesting enough to you, grab a copy on leanpub, the Amazon Kindle store, gumroad or simply checkout right down below!

Buy the Web Application Security ebook for $9.99

In the mood for some more reading?

...or check the archives.