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
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.
- Read the warning. It names the file and line where output started.
- Remove a closing ?> from files that contain only PHP.
- Send the redirect, then exit, then include the template.