W3docs

How to Fix "Headers Already Sent" error in PHP

One of the common errors that you can meet in PHP is the “Headers already sent” error. Here, we are going to show you the solution to such an error.

The “Headers already sent” warning is triggered by PHP when you call the header() function to output headers or the setcookie() function to set cookies after any content has already been sent outside of PHP tags. This tutorial will show you how to fix this error. It is one of the most widespread issues in PHP.

First and foremost, it is necessary to ensure that functions sending or modifying HTTP headers run before making any output.

Solving the Error

It is recommended to use output buffering functions to buffer the output before it is sent to the browser.

Here is how to resolve it:

<?php
ob_start();
echo "Hello World !!!";
setcookie("name", "value", time() + 3600);
echo "Again !!!";
ob_end_flush();
?>

Note: This error can also be caused by a Byte Order Mark (BOM) or accidental whitespace/newlines before the opening <?php tag. Ensure your files are saved as UTF-8 without BOM and contain no leading whitespace.

About Error Handling in PHP

The process of catching errors raised by the program and then taking relevant actions is called error handling.

Error handling is an essential part of any programming language. The process of error handling in PHP is quite straightforward.

Several functions (for example, <kbd class="highlighted">die()</kbd>) are used for dealing with PHP errors. These functions allow you to define your own error handling rules, as well as modify how errors are logged. They also help to adjust error reporting to suit your needs.

Additionally, there are logging functions. With them, you can send messages to other machines directly, to system logs, and so on.