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

Use a PHP session to keep the authenticated user’s ID available across requests, then look up that user’s name on each page that needs to show it. Start the session before sending any page output, use the same session key throughout the site, and escape the name before placing it in HTML. For forms such as comments, determine the author from the session on the server—not from a hidden field.

How PHP can show the same user on different pages

HTTP requests are separate, so a variable set during login does not automatically exist on the next page. PHP sessions provide a way to associate application data with a visitor through a unique session ID. PHP describes sessions as “a simple way to store data for individual users against a unique session ID” (PHP: Basic usage).

After verifying a login, save the authenticated account’s stable ID in $_SESSION. On another request, PHP restores the session, letting the page use that ID to retrieve the account’s current display name.

Start the session before page output

Call session_start() before HTML, whitespace, or other output on every request that needs session data. A shared bootstrap or header file is a convenient place to do this, provided it is included before the page sends output. PHP’s session documentation explains that starting or resuming a session makes its saved data available through $_SESSION (PHP: Basic usage).

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
<?php
session_start();

If the call happens after output, PHP may be unable to send the session cookie or headers correctly. Keep session startup consistent across login, protected pages, and logout.

Save the account ID after a successful login

Once the submitted password has been verified against the stored password hash, regenerate the session ID and then store the authenticated user’s ID. This prevents an existing session ID from being carried into the authenticated state. PHP’s login example follows this sequence, and its session-security guidance recommends regenerating the ID when privileges are elevated (Session security management; PHP: Examples).

<?php
// Run only after successfully verifying the password.
session_regenerate_id(true);
$_SESSION['user_id'] = (int) $user['id'];

Use one clear key, such as user_id, everywhere. In the SitePoint question, the session value named account held the database ID, not the username; printing it would display the ID, while reading $_SESSION['username'] would not work unless that key had also been assigned. The excerpts suggest this key/value mismatch, but do not establish the complete cause because the full application was not provided (SitePoint discussion).

Look up and display the name on each page

Use the session ID to fetch the username with a prepared statement. In this illustrative MySQLi example, $conn is an already configured connection and the users table has id and username columns. Adjust the binding type to match the actual ID column.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
<?php
session_start();

$username = null;
if (isset($_SESSION['user_id'])) {
    $stmt = $conn->prepare('SELECT username FROM users WHERE id = ?');
    $stmt->bind_param('i', $_SESSION['user_id']);
    $stmt->execute();
    $user = $stmt->get_result()->fetch_assoc();
    $username = $user['username'] ?? null;
}
?>

<?php if ($username !== null): ?>
    <p>Welcome, <?= htmlspecialchars($username, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') ?></p>
<?php endif; ?>

The placeholder in the query keeps the ID separate from SQL text; MySQLi’s prepared-statement workflow binds values before execution (MySQLi prepared statements). Escaping the username with htmlspecialchars() protects its insertion into this HTML text context. Use context-appropriate escaping if placing user data somewhere other than HTML text.

For a small site, the lookup can live in a shared page initialization file. Pages that do not need to show identity do not need to fetch the name, although they may still need session initialization for other login behavior.

Choose between fetching the name and storing it in the session

Approach Freshness Database work Trade-off
Store the user ID; query the name when needed Reflects a username change on the next lookup One lookup on requests that display the name Keeps authenticated identity separate from display data; use a prepared query
Store the user ID and username at login May show an old name until the session value is refreshed Avoids a name lookup on each display request Simpler rendering, but session display data can become stale

The ID-only approach is usually the clearest default: the session identifies the account, while the database remains the source for the current username. Storing a second session value is reasonable when avoiding repeated reads matters and the application has a way to refresh it after username changes.

Use the session—not a hidden field—for comment authorship

A hidden form field is still controlled by the browser user. It may be edited before submission, so a field such as <input type="hidden" name="author" value="Anonymous"> must not determine who receives credit for a comment. In the POST handler, check the authenticated session and derive the account or its name on the server. If no user is logged in, apply the site’s explicit anonymous-post policy. The SitePoint reply flags this issue in the original example (SitePoint discussion).

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

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

Use prepared statements for the comment insert as well as the username lookup when submitted values are involved (MySQLi prepared statements).

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

Security and implementation checks

  • Use a stable authenticated account ID in the session; do not treat a display name as proof of identity.
  • Regenerate the session ID after successful authentication and follow PHP’s session-security recommendations, including strict mode where appropriate (Session security management).
  • Do not interpolate a session value directly into SQL. Bind it through a prepared statement.
  • Do not use $_SERVER['HTTP_REFERER'] as a trusted redirect target. After failed login, use a fixed or allowlisted destination, or display the error locally (SitePoint discussion).
  • Verify passwords with a modern password-hashing workflow such as password_verify(); do not revert to MD5 for password storage. PHP’s authentication example uses password verification (PHP: Examples).
  • Configure secure session cookies and logout behavior for the site’s deployment; the short examples above do not provide a complete authentication system.

The code is a pattern to adapt, not a tested drop-in for an unknown application. Confirm the table and column names, MySQLi connection setup, PHP version, database ID type, and the application’s intended anonymous-user behavior.

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.