What are the advantages of using sessions to store temporary data like a shopping cart in PHP?
When building a shopping cart in PHP, using sessions to store temporary data is advantageous because it allows the data to persist across multiple pages and user sessions. This means that users can add items to their cart and continue shopping without losing their selections. Sessions also provide a secure way to store sensitive information without exposing it in the URL or using cookies.
<?php
session_start();
// Add item to shopping cart
if(isset($_POST['item_id'])) {
$item_id = $_POST['item_id'];
if(!isset($_SESSION['cart'])) {
$_SESSION['cart'] = [];
}
array_push($_SESSION['cart'], $item_id);
}
?>