Superglobals · Lesson 5 of 8
$_SESSION
Store per-user state on the server across requests.
Lesson
Sessions associate server-side data with a browser using a session identifier. Start the session before output, store only necessary data, and regenerate the ID after authentication to reduce fixation risk. Configure secure, HttpOnly, and SameSite cookie attributes and expire sessions appropriately.
Session storage is not a substitute for checking authorization on each protected request.
Further guidance
Superglobal values come from the request or process environment and can be missing or have an unexpected type. Check the key and shape before use, validate it for the operation, and avoid printing secrets or trusting client-controlled headers. Prefer the specific input source over merged request data.
Practice task: Create a fresh example for $_SESSION. Predict the result before running it, then change one input and explain why the result changes. Test a normal case and one boundary or invalid case where it applies. Compare your output with the example and note one rule you would use in a real project.
Code examples
$_SESSION
PHP
session_start();
$_SESSION['visit_count'] = ($_SESSION['visit_count'] ?? 0) + 1;
echo $_SESSION['visit_count'];
Expected output
1 on the first visit in this session
Key points
- Store per-user state on the server across requests.
- Treat request and environment values as untrusted input.
- Check the expected type and presence before using a value.
Your learning progress
Finish this lesson
Optional practice
PHP playground
This site does not execute learner-provided PHP code. Connect a secured PHP sandbox service before enabling code execution.
Execution is disabled. No code is sent to a server.