Num: Add-cart.php
<!DOCTYPE html> <html> <head> <title>Products</title> <style> .cart-badge position: fixed; top: 20px; right: 20px; background: red; color: white; padding: 10px 15px; border-radius: 50%; .product-card border: 1px solid #ddd; padding: 15px; margin: 10px; display: inline-block; .notification position: fixed; top: 20px; left: 50%; transform: translateX(-50%); padding: 10px 20px; border-radius: 5px; z-index: 1000; .notification-success background: green; color: white; .notification-error background: red; color: white; </style> </head> <body> <div class="cart-badge"> Cart Items: <span class="cart-count"><?php echo isset($_SESSION['cart']) ? array_sum($_SESSION['cart']) : 0; ?></span> </div><div class="product-card"> <h3>Product 1</h3> <p>Price: $29.99</p> <input type="number" id="qty-1" value="1" min="1"> <button class="add-to-cart-btn" data-product-id="1">Add to Cart</button> </div> <div class="product-card"> <h3>Product 2</h3> <p>Price: $49.99</p> <input type="number" id="qty-2" value="1" min="1"> <button class="add-to-cart-btn" data-product-id="2">Add to Cart</button> </div> <script> // Include the JavaScript code from above </script>
</body> </html>
session_start(); if ($_SERVER['REQUEST_METHOD'] !== 'POST') http_response_code(405); die('POST required');// CSRF check if (!hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'] ?? '')) die('Invalid request');
$productId = filter_input(INPUT_POST, 'product_id', FILTER_VALIDATE_INT); $quantity = filter_input(INPUT_POST, 'quantity', FILTER_VALIDATE_INT); add-cart.php num
if (!$productId || !$quantity || $quantity < 1 || $quantity > 99) die('Invalid product or quantity');
// Fetch product from DB and check stock // ...
$_SESSION['cart'][$productId] = ($_SESSION['cart'][$productId] ?? 0) + $quantity; Server Logic: The server processes the cart update
header('Location: cart.php'); exit;
Prevents session fixation when adding items to cart. The Result: The cart now shows a negative total (a credit)
| Symptom | Likely Cause |
|---------|---------------|
| Quantity always 1 | num not sent or empty, default triggers |
| Quantity resetting | Session not started or cart overwritten |
| Adding double | No check for existing cart item |
| Negative stock | No stock validation before cart update |
The most classic attack on add-cart.php?num= is parameter tampering. Because HTTP requests are stateless and client-side, the user has full control over the num value.