What is the significance of using sessions for managing the shopping cart across different pages in a PHP application?
Using sessions for managing the shopping cart across different pages in a PHP application is significant because it allows the user to add items to their cart on one page and access the same cart on another page without losing the cart contents. Sessions store the cart data on the server and associate it with a unique session ID, which is then used to retrieve the cart data on subsequent pages.
// Start the session
session_start();
// Add item to the cart
if(isset($_POST['add_to_cart'])){
$product_id = $_POST['product_id'];
$quantity = $_POST['quantity'];
// Check if cart is already set, if not, initialize it
if(!isset($_SESSION['cart'])){
$_SESSION['cart'] = array();
}
// Add item to cart
$_SESSION['cart'][$product_id] = $quantity;
}
// Retrieve cart items
if(isset($_SESSION['cart'])){
foreach($_SESSION['cart'] as $product_id => $quantity){
// Display cart items
echo "Product ID: $product_id, Quantity: $quantity <br>";
}
}