Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix Now×
Skip to content
header()

Using PHP `header()` to Move Between Pages Without Breaking Sessions

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Put session and redirect logic before any HTML or other output. Start the session, check the required values, send header('Location: index.php'); when the check fails, and immediately call exit;. If PHP reports “headers already sent,” the file and line named in the warning identify where output began too early.

The correct order for a protected page

session_start() creates a new session or resumes the current one. Cookie-based sessions require it to run before anything is sent to the browser. A redirect also uses HTTP response headers, so it must be issued before output.

<?php
session_start();

if (!isset($_SESSION['user_id'], $_SESSION['logged_in'])) {
    header('Location: index.php');
    exit;
}

require_once 'function.php';

// Render HTML only after the checks above.
?>

Keep this control block at the start of the request, before the document type, opening <div>, template markup, or any function that prints content.

What “headers already sent” means

HTTP headers are transmitted before the response body. Once PHP has begun sending body content, it cannot add ordinary response headers such as session cookies or a Location redirect. The PHP manual specifies that header() must run before actual output, including normal HTML, blank lines, and output produced by PHP.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The warning usually contains two locations. The earlier “output started at” file and line show where output first began; the later location is where PHP attempted session_start() or header(). For example, if output started at home.php:27 while session_start() is in header.php:5, inspect line 27 first. An opening <div> before require 'header.php'; is enough to cause the failure.

Common causes to audit

  • HTML or a PHP echo, print, warning, or notice runs before the session or redirect code.
  • An included or required file emits markup, spaces, or blank lines before control returns to the calling script.
  • A closing ?> tag is followed by a blank line or other whitespace in a PHP-only file.
  • The file begins with an invisible UTF-8 byte-order mark (BOM).
  • A diagnostic statement or accidental text was left in a bootstrap, configuration, or helper file.

Trace the earliest output, not merely the line that displays the warning. Remove the output or move the request-control block ahead of the file that produces it.

Redirecting to another page

header('Location: index.php'); sends an HTTP redirect. PHP uses a 302 response by default unless another 3xx or 201 status has been set. The browser then requests the destination and normally changes the address bar to index.php.

Always terminate the current request after sending the redirect:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
header('Location: index.php');
exit;

Without exit, PHP continues executing the remaining code, which can render content, modify state, or trigger additional headers even though the browser is being redirected.

Redirect versus rendering another page

Approach Browser address bar Use it when
header('Location: ...') Changes to the destination URL after a new request The client should navigate to a different URL, such as after a failed authentication check
Server-side routing or an include/rendering strategy Remains on the current URL The server should render a different view without making the browser request another address

Do not use a Location header when the requirement is to keep the visible URL; choose routing or server-side rendering instead.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Where to put session guards

Central bootstrap or shared header

A centralized bootstrap can start the session and enforce common authentication rules before templates load. This reduces duplicated checks, provided every protected entry point includes it before output.

Individual page checks

Page-level checks are appropriate when access rules differ, but each page must place its own session start and redirect logic before markup. A shared guard does not help an entry point that emits HTML first.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Should you use output buffering?

Output buffering can postpone transmission and sometimes masks ordering errors, but it adds buffering overhead and hidden coupling: code may appear to work only because output has not yet been flushed. Treat buffering as a deliberate, documented design choice. Placing request and session control before rendering is more predictable and makes failures easier to diagnose.

A practical troubleshooting sequence

  1. Read the warning and record the earliest “output started at” file and line.
  2. Inspect that location for HTML, whitespace, a BOM, accidental text, warnings, or printing.
  3. Check every file loaded before session_start() or header(), including require and include targets.
  4. Move session initialization and access checks to the beginning of the request, before the template.
  5. Use header('Location: ...'); followed by exit; for redirects.
  6. Reload the request and verify that the destination URL changes only when a redirect is intended.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Read next

Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.