| Low-Quality Practice | High-Quality Alternative |
|---------------------|--------------------------|
| Trusting $_POST['num'] directly | Validate + sanitize input |
| Ignoring stock levels | Check stock on each add/update |
| Using floating-point for quantity | Use integers or precise decimals |
| No CSRF protection on cart actions | Implement CSRF tokens |
| Storing cart in cookies only | Use sessions or database |
<?php session_start(); require_once 'config/database.php'; // Your DB connection require_once 'classes/CartManager.php'; // We'll build this// Only accept POST requests for adding items if ($_SERVER['REQUEST_METHOD'] !== 'POST') http_response_code(405); die(json_encode(['error' => 'Method not allowed']));
// Retrieve and validate the numeric quantity 'num' $num = filter_input(INPUT_POST, 'num', FILTER_VALIDATE_INT); $product_id = filter_input(INPUT_POST, 'product_id', FILTER_VALIDATE_INT);
// HIGH QUALITY: Strict numeric validation with reasonable defaults if ($num === false || $num === null) // Not a valid integer http_response_code(400); die(json_encode(['error' => 'Quantity (num) must be a valid integer']));
if ($num < 1) http_response_code(400); die(json_encode(['error' => 'Quantity must be at least 1']));
// HIGH QUALITY: Maximum quantity limit (business rule) $MAX_QUANTITY = 99; if ($num > $MAX_QUANTITY) http_response_code(400); die(json_encode(['error' => "Maximum quantity per item is $MAX_QUANTITY"]));
// Validate product exists and has sufficient stock // ... proceed
Why high quality? This uses FILTER_VALIDATE_INT (not intval()), which distinguishes between 0, null, and false. It rejects decimals, strings, and empty values explicitly.
A high-quality cart never trusts user input. If a user sends num=-5 or num=999999, your system must cap, correct, or reject that value.
A high-quality backend needs an equally robust frontend. Use JavaScript to enforce numeric integrity before the request reaches addcartphp.
<input type="number" id="quantity" name="num" min="1" max="99" step="1" value="1"> <button id="add-to-cart">Add to Cart</button>
<script> document.getElementById('add-to-cart').addEventListener('click', async () => num < 1 ); </script>
Create a PHP script or function that handles adding items to the cart. This example assumes you have a product ID and quantity to add.
function addToCart($productId, $quantity)
// Assuming $productId and $quantity are validated and sanitized
// Product details are fetched from the database
$product = fetchProductFromDB($productId);
if ($product)
// Check if product is already in cart
if (isset($_SESSION['cart'][$productId]))
// Update quantity
$_SESSION['cart'][$productId]['quantity'] += $quantity;
else
// Add product to cart
$_SESSION['cart'][$productId] = [
'name' => $product['name'],
'price' => $product['price'],
'quantity' => $quantity
];
else
// Handle product not found
echo "Product not found.";
// Example function to fetch product from DB
function fetchProductFromDB($productId)
// Connect to DB (example uses PDO, adjust according to your method)
$pdo = new PDO('mysql:host=localhost;dbname=yourdb', 'username', 'password');
$stmt = $pdo->prepare("SELECT id, name, price FROM products WHERE id = :id");
$stmt->execute([':id' => $productId]);
return $stmt->fetch(PDO::FETCH_ASSOC);
Let's assume you're adding a product with a unique id, name, price, and a num (quantity) you want to add.
function addToCart($id, $name, $price, $num)
// Assuming $_SESSION['cart'] is already set up
// Check if item is already in cart
foreach ($_SESSION['cart'] as &$item)
if ($item['id'] == $id)
$item['num'] += $num;
return;
// If item is not in cart, add it
$_SESSION['cart'][] = array(
'id' => $id,
'name' => $name,
'price' => $price,
'num' => $num
);
// Example usage
addToCart(1, "Sample Product", 19.99, 2);