PHP error guide
session_start cannot run after output: meaning and fix
Error summary
Start the session before response output and remove accidental bytes, debug echoes, or template rendering from bootstrap.
What it means
Start the session before response output and remove accidental bytes, debug echoes, or template rendering from bootstrap.
What the error means
session_start needs to emit or resume a session cookie, but PHP has already committed the HTTP response headers.
Why PHP produces it
Output reached the response before session initialization, making it too late to add the session cookie header.
PHP version notes
The behavior described for session_start cannot run after output applies to PHP 7.4–8.4 unless a narrower version is stated; exact wording can vary by SAPI and patch release.
Most common causes
- A PHP file contains leading whitespace or a UTF-8 BOM.
- A debug echo executes before session_start.
- The template renders before controller session initialization.
Minimal examples
BAD — reproduces the problem
echo "<h1>Hello</h1>"; session_start();
FIXED — safer pattern
session_start(); echo "<h1>Hello</h1>";
Step-by-step diagnosis
- Use headers_sent($file, $line) immediately before session_start.
- Inspect entry-point includes for BOMs and closing-tag whitespace.
- Trace middleware order to find the first response write.
Fixes
Initialize before rendering
Run session middleware before any body output.
<?php
session_start();
require __DIR__ . "/render.php";
Common mistakes when fixing it
- Globally enabling output buffering without finding accidental output.
- Adding @ before session_start.
- Calling session_start independently from multiple templates.
How to prevent it
- Keep bootstrap files free of closing PHP tags.
- Centralize session startup in middleware.
- Test response headers in integration tests.
Web server / environment notes
fpm, apache, shared-hosting. HTTP headers are committed on the first unbuffered response output.
Tags: fpm,apache,shared-hosting