Fixes & guides

Fixing "Cannot modify header information - headers already sent" in PHP

The warning names the file and line that produced output. Here is how to read it, the five usual culprits (BOM, whitespace, echo, warnings, closing tags) and fixes that do not just hide it.

On this page
  1. Step 1: go to “output started at”
  2. The five usual culprits
  3. Fixes that solve it
  4. About output buffering
Warning: Cannot modify header information - headers already sent by (output started at /var/www/app/config.php:12) in /var/www/app/login.php on line 30

HTTP headers must be sent before the body. As soon as PHP outputs a single byte, it sends the headers, and any later header(), setcookie(), session_start() or redirect fails. The message tells you both places: where output started, and where you tried to send a header.

Step 1: go to “output started at”

Open the file and line in the parentheses (config.php:12 above). That is the bug. The line in login.php is just the first victim.

The five usual culprits

1. Whitespace or HTML before <?php. A blank line or a space before the opening tag is output.

2. A UTF-8 byte order mark. Some editors add three invisible bytes (EF BB BF) at the start of a file. The warning points at line 1. Check and strip it:

head -c3 config.php | xxd        # efbb bf = BOM
sed -i '1s/^\xEF\xBB\xBF//' config.php

3. A closing ?> followed by a newline. In files that contain only PHP, leave out the closing tag entirely. PSR-12 and PER Coding Style require this.

4. echo, print, var_dump() or print_r() left in from debugging, including inside an included file.

5. A warning or deprecation printed to the page. With display_errors=On, a notice such as “Deprecated: Passing null to parameter” is itself output. After a PHP upgrade, this is the most common cause. Fix the notice, and set display_errors=Off in production (log errors instead).

Fixes that solve it

  • Move logic before output: do redirects, cookies and session_start() at the top of the request, before rendering templates.
  • Exit after redirecting:
header('Location: /dashboard/', true, 303);
exit;
  • Use a framework’s response object (Symfony Response, Laravel redirect()), which collects headers and body and sends them in the right order.
  • You can check from code: if (headers_sent($file, $line)) { error_log("Output started at $file:$line"); }.

About output buffering

ob_start() at the top of the script, or output_buffering=4096 in php.ini, holds output in memory so headers can still be sent later. It hides the symptom and can be a sensible safety net, but find the stray output anyway: a BOM or warning is still corrupting responses such as JSON or file downloads.

Found a mistake or something out of date? Tell us and we will fix it. See our editorial policy.

A good place to start

What are you working on?

Tools, guides, PHP versions and the archive.

ToolJSON ↔ PHP arrayConvert JSON to a PHP array literal with short or array() syntax, or turn a PHP array back into JSON. Runs in your browser; nothing is uploaded.ToolSerialized data inspectorRead PHP serialized strings as a tree, find wrong string lengths after a search-and-replace, and rebuild them with correct byte counts. Parsed safely in your browser.ToolComposer constraint testerSee exactly which versions a Composer constraint such as ^2.1, ~1.4 or >=8.1 <8.4 allows, in plain English, and test versions against it.ToolPHP date() format builderBuild a PHP date() or DateTime::format() string with a live preview in any time zone, plus a reference for every format character.ToolPHP upgrade checklistPick your current and target PHP versions and get every breaking change, deprecation and tooling step in between, as a checklist you can copy.GuideAllowed memory size exhaustedWhat PHP's memory_limit fatal error means, how to tell a real leak from a big job, and fixes for the usual causes: loading whole tables, unbounded arrays, Composer and recursion.GuideComposer dependency conflictsA step-by-step way to read Composer's conflict output, find the package that is blocking you, and fix it without --ignore-platform-reqs or deleting the lock file.Guidecomposer install vs updatecomposer install reproduces composer.lock; composer update rewrites it. Here is what each command does, when to use which, and a safe production deploy routine.GuideComposer uses the wrong PHP versionComposer says "your php version (8.1.x) does not satisfy that requirement" when your server runs 8.3? The cause is usually the CLI binary, config.platform.php, or platform_check.php.GuideEloquent N+1 queriesHow to spot N+1 queries in Laravel, fix them with eager loading, withCount() and constrained loads, and make Laravel throw an exception the next time one slips in.GuideHeaders already sentThe warning names the file and line that produced output. Here is how to read it, the five usual culprits (BOM, whitespace, echo, warnings, closing tags) and fixes that do not just hide it.GuideWriting a talk proposalWhat reviewers look for in a call-for-papers submission: a specific title, an abstract for attendees, notes for the committee, and a talk-sized idea. With a worked example and a checklist.GuideLaravel queue jobs not runningJobs dispatched but never processed, stuck in the jobs table, or running old code? Work through the connection, the queue name, the worker, failed jobs and deploy restarts.PHP versionsWhat's new in PHP 8.4PHP 8.4 (released 21 November 2024) brought property hooks, public private(set) visibility, new without parentheses, lazy objects, an HTML5 DOM parser and array_find(). Plus the deprecations that matter.PHP versionsWhat's new in PHP 8.5PHP 8.5 (released 20 November 2025) added the |> pipe operator, a standards-compliant URI extension, clone() with property overrides, #[\NoDiscard] and array_first()/array_last().PHP versionsWhat's new in PHP 8.6PHP 8.6 was released on 19 November 2026. Partial function application, clamp(), readonly property defaults, Io\Poll and Time\Duration, plus the session and ValueError changes to check before upgrading.GuidePHP array to JSONWhy json_encode() sometimes gives you an object instead of a list, how to keep floats and slashes intact, and how to catch the silent false that malformed UTF-8 returns.GuideDuplicate webhooks in PHPWebhook providers retry, so the same event can arrive twice. Verify the signature, record the event ID with a unique key, answer fast and process in a queue: a pattern that works in plain PHP, Laravel and Symfony.GuidePHPStan baseline for legacy codeGenerate a PHPStan baseline, stop new errors from getting in, then raise the level step by step. A tested routine for old PHP codebases.GuidePSR-4 autoloadingHow PSR-4 maps namespaces to folders, how to configure it in composer.json, and why "Class not found" happens: case, typos, a stale autoloader or a namespace that does not match the path.GuideSerialized data broken after search-replaceChanging a domain name with SQL REPLACE() or sed corrupts PHP serialized strings because their byte lengths no longer match. Here is how to spot it and repair it safely.GuideUpgrade PHP with RectorUpgrade a PHP application one version at a time: pin the baseline, let Rector rewrite syntax, let PHPStan find what Rector cannot, and prove it with tests before you switch runtimes.PHP versionsSupported PHP versionsRelease, active support and end-of-life dates for every PHP version.ArchiveSunshinePHP talk archive 2013–2020Talk titles and speakers from eight years of the Miami PHP conference.ArchiveSpeaker indexEveryone who spoke at SunshinePHP, A to Z.