How to Get Session Variable in PHP: Simple Guide
To get a session variable in PHP, first start the session using
session_start(). Then access the variable from the $_SESSION superglobal array using its key, like $_SESSION['key'].Syntax
To get a session variable in PHP, you must start the session first. Then you can access the variable from the $_SESSION array using its key.
session_start(): Initializes the session or resumes the current one.$_SESSION['key']: Accesses the session variable stored under 'key'.
php
<?php
session_start();
$value = $_SESSION['key'];
echo $value;
?>Example
This example shows how to set a session variable and then get it on the same page.
php
<?php session_start(); // Set a session variable $_SESSION['username'] = 'Alice'; // Get and display the session variable if (isset($_SESSION['username'])) { echo 'Username: ' . $_SESSION['username']; } else { echo 'No username set in session.'; } ?>
Output
Username: Alice
Common Pitfalls
Common mistakes when getting session variables include:
- Not calling
session_start()before accessing$_SESSION. - Trying to access a session variable that was never set, causing undefined index warnings.
- Forgetting to check if the session variable exists using
isset()before using it.
php
<?php // Wrong way: missing session_start() echo $_SESSION['user']; // Warning: Undefined index // Right way: session_start(); if (isset($_SESSION['user'])) { echo $_SESSION['user']; } else { echo 'User not set in session.'; } ?>
Output
User not set in session.
Quick Reference
| Step | Description | Code Example |
|---|---|---|
| 1 | Start the session | session_start(); |
| 2 | Set a session variable | $_SESSION['key'] = 'value'; |
| 3 | Get a session variable | $value = $_SESSION['key']; |
| 4 | Check if variable exists | isset($_SESSION['key']) |
Key Takeaways
Always call session_start() before accessing session variables.
Use $_SESSION['key'] to get the value of a session variable.
Check if a session variable exists with isset() to avoid errors.
Session variables persist across pages for the same user session.
Unset or destroy sessions properly to clear session data.