Solution / PHP

Cannot modify header information - headers already sent

Intermediate1 min6 Dec 2026

ErrorWarning: Cannot modify header information - headers already sent

A login script calls header() to redirect, and PHP reports that headers were already sent. The location in the warning is the first byte of body output, which is often a space, a blank line, or an echo that ran during an include.

Why it happens

  • A file starts with a blank line before <?php.
  • An included file echoes a notice, or has a closing ?> followed by a newline.
  • header() runs after some HTML in the same file.

Corrected code

PHP
<?php
declare(strict_types=1);

require __DIR__ . "/bootstrap.php";

if (empty($_SESSION["user_id"])) {
    header("Location: /login.php", true, 302);
    exit;
}

require __DIR__ . "/page.php";

The redirect happens before any template is included. exit stops the script from continuing into HTML. Leave the closing PHP tag off pure PHP files so a newline after ?> cannot become output.

  1. Read the warning. It names the file and line where output started.
  2. Remove a closing ?> from files that contain only PHP.
  3. Send the redirect, then exit, then include the template.

Related