How to use store and use session variables across pages?

How to use store and use session variables across pages?

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Session State: Why Your Cross-PAGE Checks Fail and How to Fix Them

The snippet you provided is a textbook example of a session logic error that trips up developers daily. The code fails not because session_start() is missing or misused, but because of how HTTP sessions interact with browser navigation and the specific order of operations required to establish state.

When you place $_SESSION['myvar'] = 'myvalue'; on Page A and then navigate to Page B, the session data itself is often stored correctly on the server. However, the logic inside your conditional block prevents the variable from ever being accessed if the initial assignment happens dynamically. The core issue lies in the assumption that $_SESSION['myvar'] exists immediately upon entering the second script.

The Critical Timing of Session Start

The most common reason this code "does not work" is the placement of session_start(). In PHP, a session can only be started if no other output has been sent before it. This includes whitespace, BOMs, or even echoed strings.

In your second page example:

echo("1"); // <--- ERROR
session_start(); 
if(isset($_SESSION['myvar'])) { ... }

You are echoing a string before calling session_start(). Depending on your server configuration (specifically output_buffering), this might trigger a fatal error or simply prevent the session cookie from being set correctly in the browser. The browser sends the existing cookie with the GET request, but if PHP encounters output before initializing the session handler, it cannot attach that data to the current request context properly.

The fix is strict: session_start() must be the very first line of your script.

<?php
session_start(); 
echo("1");
// Now safe to access $_SESSION

The Dynamic Assignment Trap

Even with correct session initialization, there is a second layer of complexity in your specific scenario. You are setting $_SESSION['myvar'] on Page A. If Page B is accessed via a direct link (e.g., page_b.php), the variable will not exist yet because it was set by a previous action.

Your current logic:

if($_SESSION['myvar'] == 'myvalue') {
    echo("3");
    exit;
}

This code executes only if the variable exists AND matches the value. If you navigate directly to Page B without visiting Page A first, isset($_SESSION['myvar']) returns false, and nothing happens. This is expected behavior.

However, if you are trying to enforce that a user must have visited Page A before accessing Page B, you must rely on the fact that the session persists across requests. The variable will be populated in the browser's session storage after Page A runs. As long as you don't clear $_SESSION between pages and you haven't sent output before session_start(), the data flows correctly.

Handling Session Regeneration and Security

A subtle pitfall arises if your application regenerates sessions, which is a best practice for security. If you call session_regenerate_id(true) anywhere in your flow, the session ID changes. The old cookie becomes invalid instantly. Even though the data was saved to the new session ID on Page A, the browser might still be sending the old session cookie (if it wasn't cleared) or failing to send the new one if headers were already sent.

If you implement this logic in a larger application, ensure you handle session_status() checks or simply rely on the fact that modern PHP versions manage this gracefully provided no output precedes session_start().

Integration with Frameworks like Laravel

While raw PHP sessions are powerful, they require manual cookie management and strict adherence to output buffering rules. If you are building a full-stack application, frameworks like Laravel abstract these details away. In Laravel, the session is started automatically on every request, and variables are accessible via the session() helper or Session facade without needing explicit session_start() calls in your Blade templates or Controllers.

For instance, instead of manually checking isset($_SESSION['myvar']), you would typically check if a specific key exists within the session bag provided by the framework. This reduces the risk of accidental output before initialization and ensures consistency across routes. If you are maintaining legacy PHP projects without frameworks, the strict "start first" rule remains non-negotiable.

Summary of Fixes

To make your specific code work:

  1. Ensure session_start() is the absolute first line in both Page A and Page B.
  2. Remove any echo or HTML before session_start() on Page B.
  3. Verify that you are not clearing the session array ($_SESSION = []) between pages if you intend to persist data.
  4. If using a framework, let the framework handle the session initialization and access patterns.

By respecting the lifecycle of the HTTP session cookie and the strict ordering of PHP execution, your cross-page state management will function as intended.

Our network