How to keep data in the session
Short answer
Call session_start() and work with the $_SESSION array:
<?php
session_start();
$_SESSION['cart'][] = 42;
echo count($_SESSION['cart']);Removing a value
unset() removes a single value:
<?php
session_start();
unset($_SESSION['cart']);Ending the session
When the user logs out, clear the array and destroy the session:
<?php
session_start();
$_SESSION = [];
session_destroy();Functions used in this recipe
- session_start — Starts a session or resumes the existing one.
- session_destroy — Deletes the session data on the server.
- session_regenerate_id — Gives the session a new identifier, keeping the data.