In what ways can PHP sessions be utilized to simulate a shopping cart functionality without a database?
PHP sessions can be utilized to simulate a shopping cart functionality without a database by storing the cart items in the session variable. Each time a user adds an item to the cart, it can be stored in the session variable. This allows the cart items to persist across different pages until the user completes the purchase or clears the cart.
<?php
session_start();
// Check if the cart session variable is set, if not, initialize it as an empty array
if (!isset($_SESSION['cart'])) {
$_SESSION['cart'] = [];
}
// Add item to the cart
if (isset($_POST['add_to_cart'])) {
$item_id = $_POST['item_id'];
$item_name = $_POST['item_name'];
$item_price = $_POST['item_price'];
$item = ['id' => $item_id, 'name' => $item_name, 'price' => $item_price];
// Add item to the cart array in the session
$_SESSION['cart'][] = $item;
}
// Display cart items
if (!empty($_SESSION['cart'])) {
foreach ($_SESSION['cart'] as $item) {
echo $item['name'] . ' - $' . $item['price'] . '<br>';
}
}
?>