PHP Header Errors Disrupting Your Website?

If Cannot modify header information – headers already sent by keeps appearing, unexpected output or incorrect PHP file handling may be the cause. Fix the issue before it affects redirects or sessions.

  • PHP output buffering checks
  • Header & redirect debugging
  • Whitespace & BOM fixes
  • Session handling troubleshooting
Talk to a Tech Consultant

The “Cannot modify header information – headers already sent by” error message is one of the most common errors experienced in PHP programming and WordPress. This error often occurs when PHP tries to send or change HTTP headers after the server has already started sending the response body to the client.

This error commonly occurs with redirects, session starts, cookie handling, or authentication. Any extra space, output function, or PHP error message can generate this error.

The problem faced by developers is determining the point at which the output was generated and knowing why PHP can no longer alter the response headers.

The good news is that the problem can easily be diagnosed once one understands how PHP manages the HTTP response.

This article explains the error message and how to fix it.

What Does “Cannot Modify Header Information – Headers Already Sent By” Mean?

The warning occurs when a PHP script attempts to modify HTTP headers after output has already been sent to the client.

HTTP responses contain two main components: headers and a body.

Headers provide information about the response, such as content type, cookies, caching instructions, and redirect locations. The response body contains the actual content, such as HTML, JSON, or text.

PHP normally sends headers before the response body. Once output has been transmitted, PHP cannot modify those headers.

Consider this example:

<?php
echo "Welcome to the website";
header("Location: dashboard.php");
exit;

The echo statement produces output before the redirect header is set.

If output has already been transmitted, PHP displays a warning similar to:

Warning: Cannot modify header information –

headers already sent by

(output started at /var/www/html/index.php:2)
in /var/www/html/index.php on line 4

The warning identifies where output started and where PHP attempted to modify the headers.

What Causes the Headers Already Sent Warning in PHP?

Several coding and configuration issues can trigger this warning. Most involve unexpected output before header-related operations.

Output Before the Header Function

One of the most common causes is displaying content before calling header().

For example:

<?php
echo "User authenticated";
header("Location: profile.php");
exit;

The output statement may cause PHP to send the response body before processing the redirect.

Solution:

Move the redirect logic before any output.

<?php
header("Location: profile.php");
exit;

This ensures PHP sets the redirect header before generating the response body.

Extra Whitespace Before PHP Tags

Whitespace outside PHP tags can produce output unexpectedly.

For example, spaces or blank lines before the opening <?php tag may be treated as response content.

Incorrect:

<?php
header("Location: dashboard.php");
exit;

Solution:

Ensure the opening PHP tag appears at the beginning of the file without unnecessary whitespace.

<?php
header("Location: dashboard.php");
exit;

For PHP-only files, omitting the closing ?> tag is generally recommended to prevent accidental trailing whitespace.

UTF-8 Byte Order Mark (BOM)

A UTF-8 Byte Order Mark is a sequence of bytes that may appear at the beginning of a text file.

When PHP processes a file containing a BOM before the opening PHP tag, those bytes can be treated as output.

This may trigger the headers already sent warning even when the source code appears correct.

Solution:

Open the affected PHP file in an editor such as Visual Studio Code.

Save the file using UTF-8 without BOM encoding.

Check included PHP files as well, because the unexpected output may originate from another file.

PHP Warnings or Notices Before Headers

PHP warnings displayed during script execution can also produce output.

For example:

<?php
echo $undefined_variable;
header("Location: home.php");
exit;

If PHP displays a warning about the undefined variable, the warning itself may be sent to the response body.

Solution:

Fix the underlying PHP warning rather than simply hiding it.

For production environments, configure PHP to log errors instead of displaying them to visitors.

display_errors = Off
log_errors = On

This prevents diagnostic messages from being exposed in the browser while preserving server-side error information.

How to Fix Cannot Modify Header Information – Headers Already Sent By?

The correct solution depends on where the output originates.

Step 1: Read the Complete Warning Message

Start by identifying the two file locations mentioned in the warning.

For example:

Warning: Cannot modify header information -
headers already sent by
(output started at /app/config.php:5)
in /app/login.php on line 20

Here, /app/config.php:5 identifies where output started.

The second location, /app/login.php:20, identifies the operation that attempted to modify the headers.

Inspect the first location before modifying the header function.

Step 2: Remove Unnecessary Output

Look for output-producing statements such as:

echo "Debug message";
print "Testing";
var_dump($data);

If these statements execute before header(), setcookie(), or session_start(), they may cause the warning.

Remove unnecessary output or move it after header-related operations.

Step 3: Check Included PHP Files

Sometimes the warning originates from a file loaded using include or require.

Example:

<?php
require "config.php";
header("Location: dashboard.php");
exit;

If config.php generates output, the redirect may fail.

Review included files for debugging statements, HTML content, whitespace, or a BOM.

Step 4: Verify Whether Headers Were Sent

PHP provides the headers_sent() function to determine whether response headers have already been transmitted.

<?php
if (!headers_sent($file, $line)) {
header("Location: dashboard.php");
exit;
}
error_log(
"Headers already sent in $file on line $line"
);

This helps identify the source of the problem.

However, checking whether headers were sent does not resolve the underlying issue. Developers should still correct unexpected output and application flow.

How to Fix Headers Already Sent During PHP Redirects?

Redirects are among the most common situations where this warning appears.

The header() function can send a Location response header that instructs the browser to navigate to another URL.

Incorrect:

<?php
echo "Login successful";
header("Location: dashboard.php");
exit;
Correct:
<?php
$is_authenticated = true;
if ($is_authenticated) {
header("Location: dashboard.php", true, 302);
exit;
}
echo "Authentication failed";

The redirect occurs before any response content is generated.

For login workflows, developers should also validate authentication and authorization before performing redirects.

Using exit after a redirect prevents unintended code execution.

How to Fix Headers Already Sent With PHP Sessions?

PHP sessions commonly require headers to be sent when creating or resuming a session.

If output occurs before session_start(), PHP may be unable to send the necessary session cookie.

Incorrect:

<?php
echo "Starting session";
session_start();
Correct:
<?php
session_start();
$_SESSION["username"] = "John";
echo "Session started";

Call session_start() before generating output whenever the application requires session initialization.

For larger applications, handle session management consistently during request initialization.

How to Fix Headers Already Sent When Setting Cookies?

PHP uses HTTP headers to communicate cookies to browsers.

The setcookie() function must execute before response headers are transmitted.

Incorrect:

<?php
echo "Welcome back";
setcookie("username", "John", time() + 3600);
Correct:
<?php setcookie( "username", "John", [ "expires" => time() + 3600,
"path" => "/",
"secure" => true,
"httponly" => true,
"samesite" => "Lax"
]
);
echo "Cookie configured";

The example assumes the application is served over HTTPS.

Cookie security settings should be selected according to the application’s authentication and cross-site requirements.

Can Output Buffering Fix Headers Already Sent?

PHP provides output buffering functions that temporarily store generated output before transmitting it.

For example:

<?php
ob_start();
echo "Processing request";
header("Location: dashboard.php");
exit;

Because the output remains buffered, the redirect header may still be modified.

However, output buffering should not be treated as the primary solution.

It can hide incorrect application flow, increase memory usage, and make debugging more difficult.

The preferred approach is to execute header-related operations before producing response content.

How to Prevent Headers Already Sent Errors in PHP

Preventing this warning requires consistent application structure and proper output management.

Separate Application Logic From Presentation

Process authentication, sessions, cookies, and redirects before rendering HTML.

This reduces the possibility of accidentally generating output before headers are configured.

Avoid Closing PHP Tags in PHP-Only Files

Omitting the closing PHP tag helps prevent accidental whitespace after the PHP code.

This is especially useful for configuration files, utility classes, and included scripts.

Use Consistent File Encoding

Save PHP source files using UTF-8 without BOM.

Consistent encoding reduces the risk of invisible characters appearing before the opening PHP tag.

Log Errors Instead of Displaying Them

Configure production environments to log PHP errors instead of displaying them to users.

This improves security and prevents diagnostic output from interfering with response handling.

Test Redirects and Authentication Workflows

Include redirect, session, and cookie operations in application testing.

Automated tests can help identify unexpected output and incorrect response behavior before deployment.

How Moon Technolabs Helps With PHP Development and Error Resolution

Moon Technolabs offers PHP development and web application maintenance to help companies build robust, secure, and scalable solutions. Our PHP developers can address PHP warnings, solve redirect- or session-related problems, enhance your application’s backend, and debug issues that may affect performance.

If you need to update your PHP application or resolve WordPress compatibility issues, Moon Technolabs helps you identify technical issues and implement sustainable solutions.

Conclusion

This PHP Warning, “Cannot modify header information – headers already sent by”, is thrown when PHP tries to modify HTTP headers even though some form of response has already been sent.

Several factors can cause this error, including premature echoes, extra spaces in PHP files, a UTF-8 BOM, PHP warnings visible to end users, and incorrect session or cookie ordering.

To solve the problem, examine the warning, locate the source of the output, and reposition the code that changes headers.

In WordPress, you can check theme and plugin changes and review the debug logs.

Developers should stick to coding standards to prevent these errors in the future.

author image

Explore modern web development technologies, frameworks, and methodologies for building secure, scalable, and high-performing websites and web applications. Learn about frontend, backend, APIs, architecture, performance optimization, and emerging web development trends. Stay informed about the tools and practices shaping the future of web development.

Related Q&A

bottom_top_arrow
Chat

Call Us Now

OR
OR