PHP Errors and Solutions

PHP Warning: Headers Already Sent

Fix the PHP headers already sent warning by identifying output before redirects, cookies, or session headers.

PHP Warning: Headers Already Sent

PHP must send HTTP headers before it sends the response body. This warning occurs when code tries to send a header after output has already begun.

Common Causes

Output may be caused by HTML, echo or print statements, whitespace before an opening PHP tag, a UTF-8 byte order mark, or included files that produce output.

Correct the Order

<?php
session_start();

if ($needsRedirect) {
    header("Location: /login/");
    exit;
}
?>

Start sessions and perform redirects before rendering HTML or sending other output.

Find the Source

PHP's warning often identifies the file and line where output began. Inspect that location and any files included before the failing header() call.

For PHP-only include files, omitting the closing ?> tag can help prevent accidental trailing whitespace.

Do Not Hide the Warning with Output Buffering

Output buffering can be useful in deliberate designs, but enabling it merely to hide an ordering bug can make the underlying issue harder to find.

Summary

Send cookies, session headers, and redirects before output. Inspect the first-output location reported by PHP and remove unintended whitespace or output.

Share this page Help other developers discover this resource.