Blog

Know Something new in PHP.

How to solve “Headers already sent” error in PHP?

Created by Nausin Patel on Date: 12/03/2019
  • Ensure header() calls occur before messages are written out. If functions that produce output( mentioned below) are written before header(), then it will cause this error.
  • Functions that produce output include
    print, echo, printf, vprintf
    trigger_error, ob_flush, ob_end_flush, var_dump, print
    readfile, passthru, flush, imagepng, imagejpeg

  • Remove Whitespaces before <?php and after ?>



  • Output buffering as workaround
  • PHPs output buffering is a workaround to alleviate this issue. It often works reliably, but shouldn't substitute for proper application structuring and separating output from control logic. Its actual purpose is minimizing chunked transfers to the webserver.

    It can likewise be engaged with a call to ob_start(); stop the invocation script. Which however is less reliable for multiple reasons:

    Even if starts the first script, whitespace or a BOM might get shuffled before, rendering it ineffective.

  • After header(...); you must use exit; or die;