PHP: Get username from session

PHP: Get username from session

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

Stefan Bogdanescu

Founder & Senior Architect

Accessing the Username in PHP Sessions

When debugging a PHP authentication system, it is common to encounter a situation where you can verify that a user is logged in via $_SESSION, yet the specific identifier—such as the username—appears missing from the available data. In many secure implementations, particularly those following best practices for credential storage, the session array will explicitly contain a hashed password and perhaps an integer representing a user level or role. However, the raw username is often absent because it was never stored in the session variable to begin with.

The source of this confusion usually lies in how the authentication logic interacts with the database upon login. A typical script, similar to the one referenced in community discussions, authenticates a user by comparing a submitted password against a hash retrieved from the users table. Once the credentials match, the system generates a session ID and populates the $_SESSION superglobal. The critical step here is determining what data gets written into that array. If your code sets $_SESSION['userlevel'] = $row['level'] but omits the username, you will indeed see only the hash and the level when you run var_dump($_SESSION).

To resolve this without compromising security, you must explicitly retrieve and store the username during the login process. The standard approach involves selecting the necessary columns from your database and assigning them to session variables before redirecting the user or rendering the dashboard. For example:

// Inside your authentication logic after verifying credentials
session_start();

$query = "SELECT id, username, level FROM users WHERE email = ? AND password = ?";
$stmt = $pdo->prepare($query);
$stmt->execute([$userInput['email'], $hashedPassword]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);

if ($user) {
    // Store the ID and level for permissions checks
    $_SESSION['user_id'] = $user['id'];
    $_SESSION['userlevel'] = $user['level'];
    
    // Explicitly store the username so it can be echoed later
    $_SESSION['username'] = $user['username'];
}

This pattern ensures that $_SESSION['username'] exists and contains the correct string value. When you subsequently call echo $_SESSION['username'], the output will appear as expected. It is important to understand that this does not violate security principles, provided the username is derived directly from your database records rather than being exposed in error messages or debug outputs during the login phase itself.

There are two primary reasons developers might choose not to store the full username in the session. First, some systems prefer to use the user ID (user_id) as the primary key for all subsequent queries and lookups, avoiding string comparisons where possible. Second, in highly sensitive environments, there may be a desire to minimize the amount of PII (Personally Identifiable Information) exposed if the server is ever compromised or if session data is leaked via logs. In such cases, you might store only the ID and level, then perform a fresh database lookup whenever the username is needed for display:

// If username was not stored in session
$user = $pdo->query("SELECT username FROM users WHERE id = ?", [$sessionId])->fetch();
echo htmlspecialchars($user['username']);

While this extra query adds a minor latency cost, it ensures that sensitive data isn't cached unnecessarily. However, for the vast majority of web applications, storing the username directly in $_SESSION is the most efficient and straightforward solution. It eliminates redundant database calls on every page load and simplifies the code required to display user information in headers, welcome messages, or profile pages.

If you are building a larger application where session management becomes complex, consider whether a dedicated authentication library or framework like Laravel might be more appropriate. Tools from providers like https://laravelcompany.com often encapsulate these patterns, handling session encryption and data retrieval automatically, but understanding the underlying mechanics of $_SESSION remains essential for troubleshooting custom PHP scripts.

Our network