PHP Sessions
PHP Sessions Tutorial
PHP sessions allow you to store user information on the server and access it across multiple pages. Unlike cookies, sessions are more secure because data is not stored on the client-side.
1️⃣ Starting a Session
Before using sessions, you must call session_start() at the top of the PHP page (before HTML output):
-
$_SESSIONis an associative array storing session data. -
Sessions are identified by a unique session ID.
2️⃣ Accessing Session Variables
✅ Session variables are available on all pages where session_start() is called.
3️⃣ Modifying Session Variables
4️⃣ Removing a Single Session Variable
5️⃣ Destroying a Session
-
After
session_destroy(), session variables are no longer available. -
Useful for logout functionality.
6️⃣ Example: Login Simulation with Session
login.php
dashboard.php
logout.php
7️⃣ Key Points
-
Sessions are stored on the server → more secure than cookies.
-
Use
$_SESSIONarray to store and retrieve data. -
session_start()must be called before any HTML output. -
Use
unset()to remove a single variable andsession_destroy()to remove all session data. -
Useful for login systems, shopping carts, and user preferences.
