Display a PHP session value with $_SESSION
To display a PHP session value, call session_start() before reading the key from $_SESSION. Show a fallback if it is missing and apply htmlspecialchars() before putting a string into HTML. Display only the fields you need. PHP Manual · session_start() PHP Manual · $_SESSION
Open a session and read a stored value
A session maintains server-side state across HTTP requests. In a typical cookie-based setup, the browser sends a session ID and PHP loads the matching data. Use the same session configuration on the pages that write and read. Open the session before HTML, whitespace, or echo output so PHP can send headers. Save the file without a UTF-8 BOM.
Save, read, and clear a value in one file
Use PHP 8.x with a writable session store. Save the following code as session-demo.php in a practice directory and run the command there. Open http://127.0.0.1:8000/session-demo.php. Change the port in both places if needed, and stop the server with Ctrl+C when done.
<?php
declare(strict_types=1);
ini_set('session.use_strict_mode', '1');
ini_set('session.use_only_cookies', '1');
ini_set('session.use_trans_sid', '0');
session_name('CFSESSDEMO');
$https = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' && $_SERVER['HTTPS'] !== '';
session_set_cookie_params([
'lifetime' => 0, 'path' => '/', 'secure' => $https,
'httponly' => true, 'samesite' => 'Lax',
]);
if (!session_start()) {
http_response_code(500);
exit('Could not start the session.');
}
header('Content-Type: text/html; charset=UTF-8');
header('Cache-Control: no-store');
if (!isset($_SESSION['demo_csrf']) || !is_string($_SESSION['demo_csrf'])) {
$_SESSION['demo_csrf'] = bin2hex(random_bytes(32));
}
$error = '';
if (($_SERVER['REQUEST_METHOD'] ?? '') === 'POST') {
$token = $_POST['csrf'] ?? null;
if (!is_string($token) || !hash_equals($_SESSION['demo_csrf'], $token)) {
http_response_code(403);
exit('Open the form again.');
}
$action = $_POST['action'] ?? '';
if ($action === 'clear') {
unset($_SESSION['demo_name']);
} elseif ($action === 'save') {
$raw = $_POST['name'] ?? null;
$candidate = is_string($raw) ? trim($raw) : '';
if ($candidate === '' || strlen($candidate) > 120 || preg_match('//u', $candidate) !== 1) {
http_response_code(422);
$error = 'The name must be valid UTF-8 and 1–120 bytes long.';
} else {
$_SESSION['demo_name'] = $candidate;
}
} else {
http_response_code(400);
exit('This action is not supported.');
}
if ($error === '') {
session_write_close();
header('Location: session-demo.php', true, 303);
exit;
}
}
$name = $_SESSION['demo_name'] ?? null;
$name = is_string($name) ? $name : null;
$csrf = $_SESSION['demo_csrf'];
session_write_close();
function e(string $value): string {
return htmlspecialchars($value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}
?>
<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Session value demo</title></head>
<body>
<p>Stored name: <?= $name === null ? 'None' : e($name) ?></p>
<?php if ($error !== ''): ?><p><?= e($error) ?></p><?php endif; ?>
<form method="post" action="session-demo.php">
<input type="hidden" name="csrf" value="<?= e($csrf) ?>">
<label>Sample name <input name="name" value="<?= e($name ?? '') ?>"></label>
<button name="action" value="save">Save</button>
<button name="action" value="clear">Clear the demo value</button>
</form>
<p>Selected array entry</p>
<pre><?= e(var_export(['demo_name' => $name], true)) ?></pre>
</body>
</html>
php -S 127.0.0.1:8000
- Initially there is no stored name and the array shows NULL.
- Save a sample name and check it after the 303 redirect. Reload in the same browser and it should remain.
- Open the same URL in a separate browser profile. The separate cookie store starts without a saved name.
- Clear the demo value and confirm the name disappears and the original placeholder returns.
Save and clear use POST. To protect against cross-site request forgery (CSRF), the example compares the submitted token with the session token. It checks the name’s type, length, and UTF-8 validity. After success, HTTP 303 opens a GET page so refresh does not repeat the write. CFSESSDEMO is the demo cookie name.
Display a string and a selected array entry
$_SESSION['demo_name'] ?? null yields null when the key is missing or its value is null. The example also checks that the stored value is a string, so 0 displays normally. Use array_key_exists() if you must tell a null value from a missing key.
Enter Alex & "Sam" and compare the result paragraph and the input field. The array preview copies only demo_name. It converts that array to text with var_export(..., true) and escapes the text for HTML. Keep the full $_SESSION array and the value of session_id() out of public pages. PHP Manual · htmlspecialchars() PHP Manual · var_export()
Diagnose a value that disappears between requests
Check the following in order. The browser’s developer tools can show whether the cookie was created and sent on the next request. The cookie value itself is unnecessary in logs or screenshots.
- localhost and 127.0.0.1 are different hosts. Check the URL, cookie name, and path.
- Check whether cookie blocking or an isolated cookie store leaves the cookie out of the next request.
- Check for session_start() errors, session.save_path permissions, and available disk space.
- For headers already sent, look for a BOM, whitespace, or early output from included files.
- With multiple servers, check that requests can reach the same session data.
The demo sets Secure when PHP recognizes HTTPS. In production, use HTTPS. If a proxy terminates TLS, use trusted server configuration so PHP recognizes HTTPS correctly and serves a Secure cookie. PHP Manual · session_set_cookie_params() PHP Manual · Session Security
Clear one key and close session writes
unset($_SESSION['demo_name']) removes the name and keeps the other entries, such as the token. A logout also has to handle the server-side session and cookie. session_write_close() writes the values and closes the session. Changes to the array after that are not saved, so read the data for the page first. File-based sessions can serialize requests for the same session. read_and_close is unsuitable here because the demo may need to save a token or value. PHP Manual · session_destroy() PHP Manual · session_write_close()




