PHP Fix “Warning: Cannot modify header information – headers already sent”

If you’re here, it’s probably because you are looking for answers to why you are seeing the error Warning: Cannot modify header information - headers already sent being generated from your code. There are many reasons that this can happen. Answers below…

Functions That Can Cause “Cannot Modify Header” Warning in PHP

There are many different functions that invoke this error.

What Causes The “Cannot Modify Header” Warning in PHP?

The typical cause of this type of warning happens when you are trying to modify response headers after your PHP application has already started sending a response. In the process of trying to request a webpage from the server running your PHP application, the browser expecting the response will expect a response body and response headers. In order for your browser to understand how it needs to handle the response body, it needs information from the headers. To solve this problem, PHP will send back the default response headers any time you use any of the following function calls.

  • print()
  • echo() 
  • printf()
  • vprintf()
  • trigger_error()
  • ob_flush()
  • ob_end_flush()
  • var_dump()
  • print_r()
  • readfile()
  • passthru()
  • flush()
  • imagepng()
  • imagejpeg()

So if your application calls any of these functions followed by any of the functions mentioned above, you will get this error.

Another cause of this warning is outputting HTML before calling one of the above mentioned functions. Example:

<!DOCTYPE html>

Hopefully this helps you in your exploration to develop code 🙂

Leave a Reply