PHP Sessions

PHP Sessions

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

By default, HTTP is a "stateless" protocol. When you navigate from Page 1 to Page 2 on a website, the server forgets who you are. Sessions solve this by assigning you a unique ID and storing your data securely on the server.


Starting a PHP Session

A session is started with the session_start() function.

Important: The session_start() function must be the very first thing in your document. Before any HTML tags!

Start Session Example

<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php // Set session variables $_SESSION["favcolor"] = "green"; $_SESSION["favanimal"] = "cat"; echo "Session variables are set."; ?>

</body> </html>


Getting Session Values

Once a session is started on a page, you can access the session variables on any other page on your website using the global $_SESSION variable. Just remember to call session_start() at the top of the new page too!

Read Session Example

<?php
session_start();

// Echo session variables that were set on the previous page echo "Favorite color is " . $_SESSION["favcolor"] . "."; ?>


Destroying a PHP Session

To remove all global session variables and destroy the session completely (like when a user clicks a "Log Out" button), use session_unset() and session_destroy().

<?php
session_start();

// remove all session variables session_unset();

// destroy the session session_destroy(); ?>


Exercise

?

Which function must appear before any HTML tags to start or resume a session?