πŸ”§ Error Fixes
Β· 1 min read

PHP: Cannot Modify Header Information β€” Headers Already Sent


Warning: Cannot modify header information - headers already sent

You’re trying to send headers after output has already been sent to the browser.

Why this happens

HTTP headers must be sent before any body content. PHP sends headers the moment any output occurs β€” even a single space before <?php, an echo, or a BOM (byte order mark). Once output starts, calling header(), setcookie(), or session_start() triggers this warning.

Fix 1: Move header calls before any output

<?php
// ❌ Output before header
echo "Hello";
header('Location: /dashboard');

// βœ… Headers first
header('Location: /dashboard');
exit;
?>

Fix 2: Check for whitespace before <?php

 <?php  // ❌ Space before opening tag counts as output!
<?php   // βœ… No whitespace

Fix 3: Use output buffering

<?php
ob_start();
// ... your code ...
header('Location: /dashboard');
ob_end_flush();
?>

Alternative solution: Check for BOM characters

Some editors add an invisible BOM at the start of UTF-8 files:

file yourfile.php
# If it says "UTF-8 Unicode (with BOM)", re-save as UTF-8 without BOM

Alternative solution: Omit the closing ?> tag

The closing PHP tag is optional β€” removing it prevents accidental trailing whitespace:

<?php
// Your code here β€” no closing ?> needed

Prevention

  • Configure your editor to save PHP files as UTF-8 without BOM and trim trailing whitespace.
  • Enable output_buffering = On in php.ini as a safety net for legacy projects.

Related: PHP: Undefined Index / Undefined Array Key Fix Β· How CORS Actually Works