Session variables are not persisting between page loads

Session variables are not persisting between page loads

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

Stefan Bogdanescu

Founder & Senior Architect

Session variables are not persisting between page loads

If your session data vanishes the moment a user navigates from one page to another, it usually isn't a mystery hosted on your provider's server. It is almost always a logic error in how you initialize or access $_SESSION. The code snippet you provided reveals a specific pattern that breaks session persistence: checking for session keys inside the conditional block that sets them.

The Logic Trap in Your Conditional

Look closely at this section of your code:

if(isset($_SESSION['ID']) && isset($_SESSION['token'])) {} 
else {
    $_SESSION['ID'] = $_GET['ID'];
    $_SESSION['token'] = $_GET['token'];
}

The problem lies in the if condition on line 1. This block executes on every page load where a session exists. If the user has already logged in and your code successfully populated $_SESSION['ID'] on the previous request, this condition evaluates to true. The if body is empty {}, so nothing happens.

However, the critical issue arises when you try to regenerate your token later in the script:

$mytoken = strtoupper(hash($algorithm, $secretkey.$_SESSION['ID'].$userIP.$mmdd));

This line assumes $_SESSION['ID'] is set. If your hosting environment or a specific server configuration causes session_start() to fail silently (which happens often if session.save_path is misconfigured), $_SESSION is an empty array. The isset() check passes because the keys don't exist, so the else block runs and re-reads from $_GET.

But wait, there is a more subtle bug right there. You are checking isset($_SESSION['ID']) before you have guaranteed that session_start() actually wrote to the session file. If session_start() fails to initialize (a common issue on shared hosting if the directory isn't writable), $_SESSION remains an empty array in memory. Your code then tries to read from it, finds nothing, and re-parses the URL parameters.

The real killer, however, is how you handle the token validation logic mixed with the initialization. If session_start() works perfectly, your if(isset...) block does nothing on subsequent requests. That is fine. But if session_start() fails, your code falls back to $_GET.

The "info.php" vs "info2.php" Symptom

You mentioned creating two static test files where setting the session in one file makes it invisible in the other. This confirms that the issue is not the hosting provider's PHP core breaking sessions entirely; rather, it is likely a failure to persist the session ID or a race condition in how the session is being started.

When you click a link from info.php to info2.php, the browser sends a cookie (e.g., PHPSESSID=abc123). If your server cannot write this abc123 to the disk, or if it writes it to a different path than expected, the next request arrives with a valid cookie but an empty $_SESSION array.

Your code attempts to handle this by checking isset($_SESSION['ID']). If the session is empty (because it wasn't persisted), isset() returns false, and you try to grab data from $_GET. This works for your login page because $_GET has the parameters. But on a subsequent page, if the session died, $_GET will be empty, causing your token generation to fail or throw warnings about undefined variables.

The Solution: Explicit Initialization Checks

Stop relying on implicit truthiness or isset() checks to decide whether to populate a session. Instead, explicitly check if the session is active before attempting to read from it, and always write to the session immediately after reading from $_GET.

Here is a robust pattern that avoids the logic trap:

<?php
session_start();

// Explicitly check if session data exists in memory AND in storage
if (empty($_SESSION['ID']) && isset($_GET['ID'])) {
    // Only populate if empty and GET data is present
    $_SESSION['ID'] = $_GET['ID'];
    $_SESSION['token'] = $_GET['token'];
}

// Always update activity timestamp to prevent timeout logic errors
$_SESSION['LAST_ACTIVITY'] = time();

// Generate token
$userIP = $_SERVER['REMOTE_ADDR'];
$mmdd = date('md'); // Use 'md' for month-day format, not separate variables concatenated
$mytoken = strtoupper(hash('md5', 'SECRET_KEY_HERE.' . $_SESSION['ID'] . $userIP . $mmdd));

// Validate
if ($_SESSION['token'] !== $mytoken) {
    header("Location: https://mydomain.com/login.php?returnURL=" . urlencode(curPageURL()));
    exit; // Stop execution after header redirect
}
?>

Critical Implementation Details

  1. Use empty() instead of isset(): The empty() construct returns true for empty arrays, null, false, 0, and the string "0". While isset() is often sufficient, empty() provides a clearer safety net when dealing with session initialization. More importantly, ensure you check if the data exists before trying to hash it.
  2. Handle exit after redirects: In your original code, you used header("location: ...") but continued executing script code afterwards. While not strictly fatal for a redirect, it is bad practice. Always call exit; immediately after a header redirect to prevent further logic from running.
  3. Cookie Security: Ensure your hosting environment has session.cookie_httponly=1 and session.cookie_secure=1 enabled if possible. If these are off, session hijacking is easier, which might explain why you feel the sessions are "unstable" or being tampered with.
  4. Check session.save_path: On shared hosting, ensure the directory configured for session.save_path exists and has write permissions for the web server user (often www-data). If this directory is missing or read-only, PHP will start the session in memory only. Once that script ends, the data is lost.

If you are using Laravel later, you will find that handling sessions is much cleaner with the built-in $request->session() facade, which abstracts away the $_SESSION superglobal entirely and handles persistence transparently. For now, fixing the logic flow in your PHP scripts should resolve the disappearing variables.

Our network