<?php sessionstart(); $shop = array( "4001" => array("name" => "Товар1", "price" =>…
- User
- Assistant
- User
- Assistant
To store and manage the shopping cart contents using cookies instead of PHP sessions, you'll need to adjust the logic for adding items to the cart and updating it. Here's how you can modify the existing code to use cookies:
Save Cart Data in Cookies:
Read and Update Cookie Data:
Here's a modified version of your PHP code replacing session management with cookies:
<?php
$shop = array(
"4001" => array("name" => "Товар1", "price" => 1000),
"4002" => array("name" => "Товар2", "price" => 7000)
);
if (isset($_GET['add'])) {
$productId = $_GET['add'];
if (isset($shop[$productId])) {
$cart = [];
if (isset($_COOKIE['cart'])) {
// Decode the existing cart from the cookie
$cart = json_decode($_COOKIE['cart'], true);
}
// Initialize the quantity if the product is not in the cart
if (!isset($cart[$productId])) {
$cart[$productId] = 0;
}
// Increment the quantity of the product in the cart
$cart[$productId]++;
// Save the updated cart back to the cookie
setcookie('cart', json_encode($cart), time() + 3600, "/");
}
header('Location: goods.php');
exit();
}
?>
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<title>Список товаров</title>
</head>
<body>
<h1>Список товаров</h1>
<ul>
<?php foreach ($shop as $id => $product): ?>
<li>
<?php echo htmlspecialchars($product['name']); ?> -
<?php echo $product['price']; ?> руб.
<a href="?add=<?php echo $id; ?>">Добавить в корзину</a>
</li>
<?php endforeach; ?>
</ul>
<a href="cart.php">Перейти в корзину</a>
</body>
</html>
Key Points:
json_encode to convert the PHP array into a JSON string to store it as a cookie, and json_decode to convert it back into a PHP array.time() + 3600). You can adjust this as needed."/" to make it available across your site).Note: Remember that cookies are limited in size (around 4KB), so they are suitable for storing small amounts of data like a simple shopping cart, but not large datasets.
To transition the cart management from PHP sessions to cookies for the "remove" and "remove_all" functionality, you'll need to adjust how these actions are handled. In the previous response, I explained storing the cart in cookies using JSON encoding. You'll continue with that strategy for removing and fully deleting items as well.
Here is the updated PHP code for managing the cart through cookies:
<?php
$shop = array(
"4001" => array("name" => "Товар1", "price" => 1000),
"4002" => array("name" => "Товар2", "price" => 7000)
);
if (isset($_GET['remove'])) {
$productId = $_GET['remove'];
if (isset($_COOKIE['cart'])) {
$cart = json_decode($_COOKIE['cart'], true);
if (isset($cart[$productId])) {
// Decrease product quantity
$cart[$productId]--;
if ($cart[$productId] <= 0) {
unset($cart[$productId]);
}
// Update cookie
setcookie('cart', json_encode($cart), time() + 3600, "/");
}
}
header('Location: cart.php');
exit();
}
if (isset($_GET['remove_all'])) {
$productId = $_GET['remove_all'];
if (isset($_COOKIE['cart'])) {
$cart = json_decode($_COOKIE['cart'], true);
if (isset($cart[$productId])) {
// Remove all of this product
unset($cart[$productId]);
// Update cookie
setcookie('cart', json_encode($cart), time() + 3600, "/");
}
}
header('Location: cart.php');
exit();
}
$totalPrice = 0;
?>
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<title>Корзина</title>
</head>
<body>
<h1>Корзина</h1>
<?php
$cart = isset($_COOKIE['cart']) ? json_decode($_COOKIE['cart'], true) : [];
if (empty($cart)): ?>
<p>Ваша корзина пуста.</p>
<?php else: ?>
<ul>
<?php foreach ($cart as $id => $quantity): ?>
<li>
Артикул: <?php echo htmlspecialchars($id); ?> -
<?php echo htmlspecialchars($shop[$id]['name']); ?> -
<?php echo $shop[$id]['price']; ?> руб. x
<?php echo $quantity; ?> =
<?php echo $shop[$id]['price'] * $quantity; ?> руб.
<a href="?remove=<?php echo $id; ?>">Удалить одну штуку</a> |
<a href="?remove_all=<?php echo $id; ?>">Удалить все</a>
</li>
<?php $totalPrice += $shop[$id]['price'] * $quantity; ?>
<?php endforeach; ?>
</ul>
<p>Общая цена: <?php echo $totalPrice; ?> руб.</p>
<?php endif; ?>
<a href="goods.php">Вернуться к товарам</a>
</body>
</html>
Key Changes Explained:
json_encode and json_decode to manage the cart data.time() + 3600).This approach maintains the cart state across page loads by using client-side storage (cookies) instead of server-side sessions. Remember that cookies have size limitations, so ensure that your use case fits within these constraints.
Not yet included in a published release.