How to fix “Headers already sent” error in PHP

→ Are you a new visitor? Please visit the page guidance for new visitors ←

How to fix “Headers already sent” error in PHP

Today I’ll try talking a little bit about what its called output_buffering from PHP. At least once in your life of codding you probably have seen this type of error “headers already set” from the php output, eg.

Warning: Cannot modify header information – headers already sent by (output started at /your-file.php:5) in /some/other-file.php on line 15

Now if you got here on this website, you probably think why this is happening? I can tell you straight away that the fix is a bit below this article, but I’m trying to help you understand what is going on and how to avoid this.

The reason why this happens

Basically this is pretty much a php error. You probably think I’m wrong, and you are not really wrong to say that, but not right either. The issue is that when you try to start a session for example in multiple files, you are already starting an output, hence you send headers to your browser. But in most cases, you would need to start the session in all files that you will be using, correct?

Wrong! You do not need to add the session_start() directives in all files unless you access those files directly and browser needs to understand that there should be a session that needs to be used. For example when including files or requiring another file in a specific public file, eg. the index.php page, you do not need to start a session in all the included files since its not needed.

Of course this is only a small example where I’ve seen some users doing this, issue can also happen when manipulating headers, the same thing happens.

So basically what you need to do is just to carefully fix the code so that you only send headersĀ once per page load.

Easy solution

The code is a mess, I can’t go over all my code, isn’t there an easy fix for this?

There is, but comes with a little more CPU usage. The easiest thing to do would be to enable output_buffering in your PHP configuration or php.ini

or, if your hosting provider allows php_value / php_flag in your .htaccess, you can use:

What this does is buffer the entire output of your page in memory and once completed it will send output to your browser and avoid sending headers twice to your browser.

This is the easy fix, but again, comes with a small margin of more CPU usage.

That’s it for now, see you again tomorrow.

Request an article ←