If you are working on PHP, chances are you might familiar with Cannot Modify Header Information, Header Already Sent ErrorĀ . In this post i am trying to explain what is the actual cause of Header already sent error and how you avoid this.
Before we dig into this error, first let us know what is Header
Header is generated automatically, it is the medium through which browser and server communicates. It contains information about the page, content-type, last-modified ,session and cookies etc. You can see the header request and response on chrome developer tool, i put one screenshot below . If you are using Mozilla then you can check on firebug.
Here is one example of header.
1 2 3 4 5 6 7 |
Accept-Ranges:bytes Age:14 Content-Length:1985 Content-Type:image/png Date:Sun, 28 Jul 2013 06:55:09 GMT Last-Modified:Mon, 11 Mar 2013 01:04:28 GMT Server:Apache |
How to Avoid Cannot Modify Header Information, Header Already Sent Error
This error occurs when some content has already been sent to the web browser and then a header is set (setting a cookie, Redirecting a page through header method, session start and so on).
To avoid this error Headers must be sent before sending any content.
1. Always put header information in top.
for example-
1 2 3 4 5 |
<html> <head> </head> <?php header('Location: https://www.webrewrite.com/'); ?> |
This will give an error. Put header code on top to avoid error. header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP. To know more about header() function in php.
2. Enable output buffering . Using ob_start().
3. No white space outside of php start and end tags. The reason behind this is when it processed by php, it will turn into a echo printing blank line.