PromptHub
PHP Intermediate 15 views

Headers Already Sent

The code tries to send HTTP headers after output has already been sent to the browser.

Explanation

Headers already sent error occurs when PHP tries to send HTTP headers (via header(), setcookie(), or session_start()) after some output has already been sent to the browser. HTTP headers must be sent before any body content. The error message indicates the file and line number where the output started. Common causes include whitespace or BOM characters before the opening PHP tag, echo/print statements before headers.

Common Causes

  • Whitespace before opening PHP tag
  • BOM characters in UTF-8 files
  • Echo/print before header calls
  • Included file with trailing ?> tag
  • Session start after output

Solution

Ensure no output occurs before headers: remove any whitespace or HTML before the opening <?php tag. Use output buffering (ob_start()) in configuration files. Check all included files for trailing ?> tags or whitespace. Verify no echo/print statements exist before redirects or session operations. In Laravel, use the return statement with redirect() rather than calling it after output.

Code Example

<?php
  echo 'Hello'; // output sent
  header('Location: /other'); // Error: headers already sent
?>

// Fix: remove output before headers
<?php
  header('Location: /other');
  exit;
?>

// Enable output buffering in php.ini
output_buffering = 4096

// Or use ob_start()
ob_start();
// ... code ...
header('Location: /redirect');
ob_end_flush();

Error Information

Language

php

Difficulty

Intermediate

Views

15

Related Errors