How to store a variable in php using session

How to store a variable in php using session

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

Stefan Bogdanescu

Founder & Senior Architect

Understanding PHP Session Storage Syntax and Logic

A common stumbling block for developers transitioning from standard variables to session storage is misunderstanding how the $_SESSION superglobal interacts with variable assignment. The confusion often stems from conflating the act of starting a session, retrieving an existing value, or storing a new one. In your specific example, you attempted to use session_id($id) and $_SESSION['$id'], both of which fail because they target different aspects of the session mechanism entirely.

The function session_id() is designed exclusively for retrieving the current session ID string or setting it manually via a string argument. It does not store data within the session array. Consequently, calling session_id($id) when $id equals 10 simply returns "10" as a string and prints it; it does not persist that value anywhere on the server. To actually store data, you must interact with the $_SESSION superglobal array directly.

The second attempt, $_SESSION['$id'], introduces a critical syntax error regarding variable interpolation. In PHP, square brackets used for array access do not automatically interpolate variables unless they are enclosed in curly braces {}. When you write $_SESSION['$id'], the server literally interprets this as looking for a key named '$id' (including the quotes and letters). It never looks for the value of $id. To fix this, you must use curly braces: $_SESSION[$id]. This syntax tells PHP to evaluate $id first and then use that result as the array key.

Here is the correct implementation to store your variable:

// Ensure a session exists before attempting to write
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

$id = 10;

// Correct syntax using curly braces for interpolation
$_SESSION[$id] = "User ID is $id"; // Storing the value as a string or object

echo $_SESSION[$id]; 

In this corrected code, session_status() checks if a session has already been started. If not, session_start() initializes it. Once initialized, assigning to $_SESSION[$id] places the data into the session file (or cookie, depending on configuration) associated with that specific user's browser. When you retrieve it later in another request, the key remains $id, which evaluates to 10.

There are significant trade-offs and pitfalls to consider when choosing this approach over a simple global variable or database lookup. First, relying on dynamic keys like $_SESSION[$id] can make debugging difficult. If you iterate over your session array later using array_keys($_SESSION), you will see numeric keys mixed with string keys depending on how they were assigned. This makes it harder to distinguish between data stored intentionally and data that might have leaked in.

Second, security implications are paramount. Storing sensitive data like passwords or API keys in sessions is a cardinal sin of web development. Sessions should only store non-sensitive identifiers, user preferences, or temporary tokens that expire quickly. If you need to persist complex objects, consider serializing them using serialize() and storing the resulting string, though this increases payload size.

If you are working within a Laravel ecosystem, handling sessions is abstracted away slightly but follows similar principles. While you can manually access session($key), frameworks encourage using service providers or model observers to manage session state more cleanly. For instance, instead of scattering $_SESSION[$id] assignments across controllers, you might create a dedicated trait or repository method that handles session injection, ensuring consistency and making testing easier.

Ultimately, the distinction between session_id(), $_SESSION['literal'], and $_SESSION[$variable] is fundamental. Mastering this syntax ensures that data persists correctly across requests without relying on fragile state management or exposing sensitive information in predictable ways.

Our network