Sessions in PHP
A session enables developers to keep track of information (variables) throughout various pages within a web application. The session serves to monitor user activity such as login status while simultaneously storing temporary data.

Why Use Sessions?
- Store user data (e.g., name, email, role)
- Track login/logout status
- Preserve shopping cart contents
- Avoid exposing data in URLs (like $_GET)
Starting a Session
Always call session_start() at the beginning of your script before any output:
<?php session_start(); ?>
Setting Session Variables
<?php session_start(); $_SESSION["username"] = "Alice"; $_SESSION["role"] = "admin"; echo "Session variables are set."; ?>
Accessing Session Variables
<?php session_start(); echo "Username: " . $_SESSION["username"]; echo "Role: " . $_SESSION["role"]; ?>
Unset a Session Variable
<?php session_start(); unset($_SESSION["username"]);
Destroying a Session
<?php session_start(); session_destroy(); // Deletes all session data ?>
Session vs Cookie
| Feature | Session | Cookie |
|---|---|---|
| Stored Where | Server | Client (browser) |
| Secure? | More secure | Less secure |
| Size Limit | Larger | ~4KB |
| Lifespan | Ends with browser or timeout | Persistent (if set) |
Session Function
| Task | Function |
|---|---|
| Start session | session_start() |
| Set session | $_SESSION['key'] = value; |
| Get session | $_SESSION['key'] |
| Unset session var | unset($_SESSION['key']); |
| Destroy session | session_destroy(); |
Quickly Find What You Are Looking For
OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.
point.com