PHP Basics

Simple fix for Header already sent error in PHP Scripting

While setting header information we often encounter this error: header already sent and we could not able to figure out exactly what is the error and how to solve it.

Headers Already Sent Error

First of all we have to understand why this error is rising.

Reason

When ever we run a php script, along with the html data the server sends header information.

Example

HTTP/1.1 200 OK

Powered-By: PHP/5.3.7

Vary: Accept-Encoding Content-Type: text/html;

charset=utf-8

<html>

<head><title>Example Site</title></head>

<body>

<h1>Example Site</h1>

<p>Some sample paragraph text</p>

</body>

</html>

 

In the above example, the header information is sent along with the html.

So when ever a webpage is requested by a browser, the browser looks for theĀ header information. This header information should available only once and at the top of the webpage.

What causes headers already sent error?

Something has printed before the user defined headers. Therefore a header is already sent before the user defined header could have reached to the browser.

Whitespace

Whitespace before the php code could cause the error. So check if there are any white space before the php opentin tag (<?php)

Print or echo

If user unintentionally included print or echo function inside the user defined headers function then also it will raise the mentioned error.

So remove any print or echo function in the php code.

HTML tags

Presence of html tags before php script could also result in the mentioned error. So remove html tags before the php code.

Solution

In the above, it is mentioned what causes the error. If we check whether the mentioned reasons is causing the error then all we have to do is work on the root reason. It will solve headers already sent error in php.