PHP Sessions

PHP Sessions

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(); // Starts a session
  • session_start() must be the first thing before any HTML output.

Example: Starting a Session

<?php session_start(); // Start the session $_SESSION["username"] = "JohnDoe"; // Store session data $_SESSION["role"] = "admin"; echo "Session variables are set!"; ?>

What Happens?

  • A session ID is created and sent to the user’s browser.
  • The session variables username and role 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

<?php session_start(); // Resume session echo "Welcome, " . $_SESSION["username"] . "!<br>"; echo "Your role is: " . $_SESSION["role"]; ?>

Output:

Welcome, JohnDoe! Your role is: admin

4. Checking if a Session Variable is Set

<?php session_start(); if (isset($_SESSION["username"])) { echo "Hello, " . $_SESSION["username"]; } else { echo "No user is logged in."; } ?>

5. Destroying a Session

5.1. Unset Specific Session Variables

unset($_SESSION["username"]); // Remove 'username' only

5.2. Destroy Entire Session

session_destroy(); // Ends the session completely
  • 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)

<form action="login.php" method="POST"> Username: <input type="text" name="username"><br> Password: <input type="password" name="password"><br> <input type="submit" value="Login"> </form>

6.2. Login Processing (login.php)

<?php session_start(); // Start session // Dummy user data $valid_user = "admin"; $valid_pass = "1234"; if ($_POST["username"] == $valid_user && $_POST["password"] == $valid_pass) { $_SESSION["username"] = $_POST["username"]; header("Location: dashboard.php"); // Redirect to dashboard } else { echo "Invalid username or password."; } ?>

6.3. Dashboard (dashboard.php)

<?php session_start(); if (!isset($_SESSION["username"])) { header("Location: login.html"); // Redirect if not logged in exit(); } echo "Welcome, " . $_SESSION["username"] . "!"; ?> <a href='logout.php'>Logout</a>

6.4. Logout (logout.php)

<?php session_start(); session_destroy(); header("Location: login.html"); // Redirect to login page ?>

7. Session Timeout (Auto Logout)

PHP allows setting a session timeout for security.

Example: Set Session Timeout (session_timeout.php)

<?php session_start(); // Set session timeout to 5 minutes (300 seconds) $timeout = 300; if (isset($_SESSION["last_activity"]) && (time() - $_SESSION["last_activity"]) > $timeout) { session_unset(); // Unset session variables session_destroy(); // Destroy session header("Location: login.html"); // Redirect to login exit(); } $_SESSION["last_activity"] = time(); // Update last activity timestamp ?>

8. Storing and Retrieving Session Data

Example: Store User Preferences in Session

<?php session_start(); $_SESSION["theme"] = "dark"; // Storing theme preference echo "Your selected theme is: " . $_SESSION["theme"]; ?>

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 in php.ini.

Check Session Storage Path

echo session_save_path();

10. Secure Session Handling

10.1. Regenerate Session ID to Prevent Session Hijacking

session_regenerate_id(true); // Generates a new session ID

10.2. Restrict Session to HTTPS

session_set_cookie_params([ 'secure' => true, // Only send cookie over HTTPS 'httponly' => true, // Prevent JavaScript access 'samesite' => 'Strict' // Prevent CSRF attacks ]); session_start();

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!

Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close