Sling Academy
Home/PHP/How to Fix PHP Warning: Headers Already Sent – Cannot Modify Header Information

How to Fix PHP Warning: Headers Already Sent – Cannot Modify Header Information

Last updated: January 14, 2024

Overview

If you’re a PHP developer, you might have come across the warning ‘Cannot modify header information – headers already sent,’ a common issue that often baffles newcomers and seasoned developers alike. This warning is triggered when your PHP script tries to send a header to the client after any output has been already sent.

This tutorial provides a comprehensive walkthrough for fixing the ‘headers already sent’ warning in PHP.

Understanding the Problem

Headers in PHP need to be sent to the browser before any kind of output is sent. The output can be HTML, plain text, or even whitespace; any output before the header function calls will trigger the warning, as per the HTTP protocol you cannot modify headers after output has started.

Common Causes:

  • Printing or echoing output before calling header functions.
  • Whitespace or newlines before PHP opening tags <?php or after closing tags ?>.
  • UTF-8 byte-order mark (BOM) at the beginning of the file.
  • Inclusion of files that output something.
  • Incorrectly closed PHP tags or forgotten inline HTML.

Diagnosing the Issue

To diagnose the error, start by looking at the error message itself. It will tell you the file and the line number where the output started:

Warning: Cannot modify header information - headers already sent by (output started at /path/to/php/file.php:2) in /path/to/php/file.php on line 10

Go to the specified file and line to see what might be sending the output.

Fixing the Issue

Eliminate Whitespace and BOM

Ensure there is no whitespace before <?php and after ?>. If your text editor supports it, enable the setting to remove the BOM.

// Incorrect:
?>
<?php
// Correct:
<?php

Avoid Premature Output

Avoid echoing or printing data before calling header functions. Use output buffering if necessary. Start output buffering at the beginning of your script with ob_start() and end it with ob_end_flush().

<?php
ob_start();
// your code
echo 'Hello, World!';
header('Location: http://www.example.com');
ob_end_flush();
?>

Inclusion of Files

Make sure any files you include do not send output. Double-check included scripts for whitespace, especially at the end of the file.

File Encoding

Save your PHP files with UTF-8 encoding without BOM.

Using Exit

Make sure to call exit() after sending a header, especially when redirecting. This ensures the script stops executing and does not send any unintended output.

header('Location: http://www.example.com');
exit;

Best Practices

Consistent Code Structure

Organize your code to handle all logic and data processing before output. Manage headers and redirects at the beginning of your scripts.

Removing Closing PHP Tag

In pure PHP files, it’s a common practice to omit the closing PHP tag ?> to prevent accidental output.

Use Output Buffering

Output buffering can simplify handling of output, although it’s not always the best fix, understanding why output is being sent prematurely is usually more beneficial.

Common Pitfalls

Headers Sent in Included Files

Remember that included or required files are treated as a part of the file that called them. Ensure they do not send headers or output.

Early Session Starts

Calling session_start() and similar functions also sends headers. Use them cautiously and in the proper location in your script.

Conclusion

Dealing with the ‘headers already sent’ warning in PHP is mostly about understanding the output flow of your PHP files. In development, always keep error reporting at the highest level to catch these issues early by using error_reporting(E_ALL) and ini_set('display_errors', 1).

Adhering to the best practices outlined in this tutorial will not only help you fix the ‘headers already sent’ warning but also improve the overall quality of your PHP projects.

Next Article: How to Set Up PHP Composer in MacOS

Previous Article: PHP: Calculate a future date from a given date

Series: Basic PHP Tutorials

PHP

You May Also Like

  • Pandas DataFrame.value_counts() method: Explained with examples
  • Constructor Property Promotion in PHP: Tutorial & Examples
  • Understanding mixed types in PHP (5 examples)
  • Union Types in PHP: A practical guide (5 examples)
  • PHP: How to implement type checking in a function (PHP 8+)
  • Symfony + Doctrine: Implementing cursor-based pagination
  • Laravel + Eloquent: How to Group Data by Multiple Columns
  • PHP: How to convert CSV data to HTML tables
  • Using ‘never’ return type in PHP (PHP 8.1+)
  • Nullable (Optional) Types in PHP: A practical guide (5 examples)
  • Explore Attributes (Annotations) in Modern PHP (5 examples)
  • An introduction to WeakMap in PHP (6 examples)
  • Type Declarations for Class Properties in PHP (5 examples)
  • Static Return Type in PHP: Explained with examples
  • PHP: Using DocBlock comments to annotate variables
  • PHP: How to ping a server/website and get the response time
  • PHP: 3 Ways to Get City/Country from IP Address
  • PHP: How to find the mode(s) of an array (4 examples)
  • PHP: Calculate standard deviation & variance of an array