HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

PHP $_SESSION

A session is a way to store information (in variables) to be used across multiple pages. Unlike a cookie, the information is not stored on the user's computer; it is stored on the server.


1. Starting a Session

A session is started with the session_start() function. This must be the very first thing in your document, before any HTML tags.

<?php
    session_start();
?>
<!DOCTYPE html>
<html>
<body>
    <!-- Content -->
</body>
</html>

2. Storing Session Variables

You can store data in the $_SESSION superglobal array. These variables will be available on all other pages in the same site.

<?php
    session_start();
    $_SESSION["favcolor"] = "green";
    $_SESSION["favanimal"] = "cat";
    echo "Session variables are set.";
?>

3. Retrieving Session Variables

To access session data on a different page, you just need to call session_start() again and read from the $_SESSION array.

<?php
    session_start();
    echo "Favorite color is " . $_SESSION["favcolor"] . ".";
?>

4. Destroying a Session

To logout a user or clear all session data, you should use both session_unset() and session_destroy().

<?php
    session_start();
    session_unset();   // remove all session variables
    session_destroy(); // destroy the session 
?>
Why use Sessions? HTTP is "stateless," meaning the server doesn't remember who you are between page clicks. Sessions solve this by giving the user a unique ID (the Session ID) stored in a cookie, which the server uses to retrieve your data.
Pro Tip: Use isset($_SESSION['user_id']) at the top of protected pages to check if a user is logged in. If not, you can redirect them to the login page.

Key Takeaways

  • Always call session_start() at the top of the file.
  • Server-side storage: Data is safer than in cookies.
  • Sessions end when the user closes the browser (by default).
  • Use session_unset() before session_destroy() for a clean logout.