PHP Tips – Warning: Cannot modify header information. Let’s get things straight

Tell me the truth: you have had to mix it up with this error at least once, haven’t you?
In this pill we’ll get things straight, once and for all, how this error occurs, how to avoid it and, if it’s not possible to avoid it, how to eventually bypass it.

When does this error come up?

Some PHP functions add some information to the headers which the web server sends to the browser when a page is requested. The main functions of this kind are:

  • header()
  • setcookie()
  • session_start()

As soon as we have an output in a document (any output), the web server starts sending the headers to the client. This, for example, is the header that Your Inspiration Web sends me

Date: Mon, 01 Nov 2010 13:55:15 GMT
Server: Apache/2.2.15 (Unix) mod_ssl/2.2.15 OpenSSL/0.9.8e-fips-rhel5 mod_auth_passthrough/2.1 mod_bwlimited/1.4 FrontPage/5.0.2.2635
X-Powered-By: PHP/5.2.13
Vary: Cookie
Expires: Wed, 11 Jan 1984 05:00:00 GMT
X-Pingback: http://www.yourinspirationweb.com/xmlrpc.php
Cache-Control: no-cache, must-revalidate, max-age=0
Pragma: no-cache
WP-Super-Cache: Served legacy cache file
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Transfer-Encoding: chunked
Content-Type: text/html; charset=UTF-8

200 OK

If I set a cookie, a row like this would be added
Set-Cookie: name=value; expires=timestamp of cookie expiration

Now, if we write

echo “Hello”;
 

the web server will release the headers as soon as it meets this instruction.
At this point having done that, if I wanted for example to set a cookie, I would no longer be able to. In fact, the cookie data are sent to the request header, but the header has already been launched and thus the infamous error will come up.

I repeat: any output

This script also will lead to the notorious error


<?php // notice that there's a “new paragraph ” before the opening of the php tag
session_start();
 //....
 

In fact before the opening of the PHP tag we are in HTML mode, and in this modality a “new paragraph” is, whether you want it or not, an output.
By the way, often the error is exactly this (and maybe it’s an error contained in some file comprised and that makes us lose a lot of precious time)!

Solutions

The solution is obviously to use functions that modify the header at the beginning of the script, or however, before any output. This can be done in 99,5% of the cases, even when it might look impossible, and it’s the best solution.
However, in rare circumstances, this procedure might not be possible.
In this case we could use the ob_start() function (to be invoked at the beginning of the script). This function keeps the output in buffer until the end of the execution of the script.
Therefore this script will not lead to errors:

<?php ob_start(); ?>
<h1>Hello</h1>
<?php session_start(); ?>

This  solution is to be used with thrift because the storage of outputs on the server will have a burden on the performance. We can partially overcome this problem liberating the buffer once there is no longer need for it through the ob_end_flush() function.

<?php ob_start(); ?>
<h1>hello</h1>
<?php
session_start();
ob_end_flush();
//other code and other content....
?>

Conclusion

In this pill we dealt with what is considered a headache for many, in reality it’s just a trivial thing which can be resolved with a minimal effort.
And you? Have you ever got stuck with this error?

Master per Web Designer Freelance
In tutti questi anni abbiamo ricevuto centinaia di richieste di approfondimento sulle numerose tematiche del web design vissuto da freelance. Le abbiamo affrontate volta per volta. Ma ci siamo resi conto che era necessario fare qualcosa di più. Ecco perché è nato One Year Together, un vero e proprio master per web designer freelance che apre finalmente le porte al mondo del lavoro.
Scopri One Year Together »
[pdf]Scarica articolo in PDF[/pdf]
Tags:

The Author

Maurizio is married to the triad PHP - MySql - Apache and, not enough, he has a lover called jQuery. He has a blog where he tries to describe in detail all of "his lovers". His real specialty is the realization of large business application, altough he never refuses the commitment of a website.

Author's web site | Other articles written by

Related Posts

You may be interested in the following articles:

8 comments

  1. hqxaj
  2. rama krishna

Trackback e pingback

  1. Tweets that mention PHP Tips – Warning: Cannot modify header information. Let’s get things straight | Your Inspiration Web -- Topsy.com
    [...] This post was mentioned on Twitter by soshableweb and Tom Bangham, V. Tavares (E-Goi). V. Tavares (E-Goi) said: PHP …

Leave a Reply

Current day month ye@r *