// 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']));
Replace the redirect blocks with a structured JSON response helper function: addcartphp num high quality
This uses FILTER_VALIDATE_INT (not intval() ), which distinguishes between 0 , null , and false . It rejects decimals, strings, and empty values explicitly. // HIGH QUALITY: Strict numeric validation with reasonable
For highly sensitive cart transitions (like adding items from a third-party link simulation), cross-verify a unique cryptographic token stored in user sessions against incoming requests. Conclusion $qty) $productId = (int)$productId
foreach ($_POST['quantities'] as $productId => $qty) $productId = (int)$productId; $qty = filter_var($qty, FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]);
$_SESSION['cart'] = [ 123 => 2, // product_id => quantity 456 => 1 ];