PHP Sessions
A session in PHP is a way to store user-specific information across multiple pages. Unlike cookies, session data is stored on the server rather than the client’s browser, making it more secure.
1. What is a PHP Session?
- A session allows data to persist across different pages during a user’s visit.
- PHP uses a unique Session ID (
PHPSESSID
) to track users. - Session data is stored on the server (usually in temporary files).
- A session ends when the user closes the browser or after a specified timeout.
2. Starting a PHP Session
Syntax:
session_start()
must be the first thing before any HTML output.
Example: Starting a Session
What Happens?
- A session ID is created and sent to the user’s browser.
- The session variables
username
androle
are stored on the server.
3. Accessing Session Data
Once session variables are set, they can be accessed on any page.
Example: Accessing Session Data on Another Page
Output:
4. Checking if a Session Variable is Set
5. Destroying a Session
5.1. Unset Specific Session Variables
5.2. Destroy Entire Session
session_destroy()
removes all session data, but the session ID remains until the browser is closed.
6. Example: Complete Login System with Sessions
6.1. Login Form (login.html)
6.2. Login Processing (login.php)
6.3. Dashboard (dashboard.php)
6.4. Logout (logout.php)
7. Session Timeout (Auto Logout)
PHP allows setting a session timeout for security.
Example: Set Session Timeout (session_timeout.php)
8. Storing and Retrieving Session Data
Example: Store User Preferences in Session
9. Where are PHP Sessions Stored?
- On most servers, session data is stored in the
/tmp
directory. - You can change the location using
session.save_path
inphp.ini
.
Check Session Storage Path
10. Secure Session Handling
10.1. Regenerate Session ID to Prevent Session Hijacking
10.2. Restrict Session to HTTPS
Conclusion
- Sessions allow storing user data across multiple pages.
- Use
session_start()
before outputting anything. - Always unset or destroy sessions after logout for security.
- Implement session timeouts and secure cookie settings.
By using PHP Sessions, you can create secure and personalized web applications!