Add-cart.php Num — No Ads
To develop solid content for an add-cart.php script that handles a quantity parameter (often referred to as num or quantity), you need a secure way to process product additions and updates in the user's session. Core Logic for add-cart.php
The script should follow these functional steps to ensure reliability:
Initialize Session: Always start with session_start() to access the user's cart data.
Sanitize Inputs: Retrieve the product ID and the "num" (quantity) from $_GET or $_POST. Use type casting (e.g., (int)) to prevent injection attacks.
Validate Data: Ensure the product exists in your database and that the requested quantity is a positive integer.
Update Cart: Check if the product is already in the $_SESSION['cart']. If it exists: Add the new "num" to the existing quantity. If it's new: Initialize it with the provided quantity. Implementation Example Here is a secure implementation using PHP sessions:
// 1. Capture and sanitize inputs $product_id = isset($_POST['id']) ? (int)$_POST['id'] : 0; $num = isset($_POST['num']) ? (int)$_POST['num'] : 1; // 2. Basic validation if ($product_id > 0 && $num > 0) // Initialize cart if it doesn't exist if (!isset($_SESSION['cart'])) $_SESSION['cart'] = []; // 3. Update quantity logic if (isset($_SESSION['cart'][$product_id])) // Increment if already present $_SESSION['cart'][$product_id] += $num; else // Add as new entry $_SESSION['cart'][$product_id] = $num; // Optional: Redirect to cart page after success header("Location: cart.php?status=added"); exit(); else // Handle error (invalid ID or quantity) header("Location: products.php?error=invalid_request"); exit(); ?> Use code with caution. Copied to clipboard Essential Features to Include Cart Functions and how to do them in PHP - DEV Community
Here’s a helpful write‑up for add-cart.php focusing on the num parameter — how it works, security concerns, and best practices. add-cart.php num
Case Study: Exploiting add-cart.php?num=
Let’s walk through a real-world penetration test scenario.
Target: https://vintage-books.com/add-cart.php?num=12
Step 1 – Fuzzing: The attacker uses Burp Suite to fuzz the num parameter with a payload list: 1, 1.1, -1, 999999, 1 UNION SELECT 1, 1%00.
Step 2 – Discovery: A request to add-cart.php?num=1.1 returns a MySQL error: "Unknown column '1.1' in 'where clause'" — SQL injection confirmed.
Step 3 – Exploitation: The attacker crafts add-cart.php?num=12 AND 1=2 UNION SELECT database()-- -. The cart page inadvertently displays the database name (e.g., "vintage_store_db") because the product name lookup fails and falls back to the error message.
Step 4 – Escalation: Within minutes, the attacker has extracted table names, dumped admin credentials, and is now logged into the admin panel. All from a single num parameter.
Anatomy of a Standard Add-to-Cart Request
Before diving into exploits, let’s look at a typical HTTP request: To develop solid content for an add-cart
POST /add-cart.php HTTP/1.1 Host: example.com Content-Type: application/x-www-form-urlencoded Cookie: PHPSESSID=abc123
product_id=456&num=3&option=size_l
Or, via GET method (less secure, but common):
/add-cart.php?product=456&num=3
The num parameter (often named qty, quantity, or count) tells the backend how many units of a product to place into the session array.
Step 2: The "Insert or Update" Logic
This is the most crucial logic block. If a user clicks "Add to Cart" twice for the same product, you generally don't want two separate rows in your database. You want to increase the quantity of the existing row.
There are two ways to handle this:
- Select first, then Insert/Update: (Runs two queries).
- ON DUPLICATE KEY UPDATE: (Efficient, runs one query).
We will use the efficient MySQL approach: INSERT ... ON DUPLICATE KEY UPDATE. Case Study: Exploiting add-cart
Note: For this to work, you need a Unique Index on user_id and product_id combined in your database table.
try // Begin Transaction for data integrity $pdo->beginTransaction();// The Query // This attempts to insert the row. // If the user_id + product_id combo already exists, it updates the quantity instead. $sql = "INSERT INTO cart_items (user_id, product_id, quantity) VALUES (:user_id, :product_id, 1) ON DUPLICATE KEY UPDATE quantity = quantity + 1"; $stmt = $pdo->prepare($sql); // Bind Parameters (Prevents SQL Injection) $stmt->bindParam(':user_id', $user_id, PDO::PARAM_INT); $stmt->bindParam(':product_id', $product_id, PDO::PARAM_INT); $stmt->execute(); // Commit changes $pdo->commit(); // Redirect user back to cart or product page header("Location: cart.php?success=added"); exit(); catch (PDOException $e) // Rollback if error occurs $pdo->rollBack(); error_log("Cart Error: " . $e->getMessage()); header("Location: products.php?error=database_error"); exit();
Step 1: Initialization and Input Sanitization
The script usually receives data via a GET or POST request. Let's assume the request looks like add-cart.php?id=123.
<?php session_start();// 1. Include Database Connection require_once 'db_connect.php'; // Assume $pdo is the connection object
// 2. Check if the request is valid if (isset($_GET['id']))
// 3. Sanitize the Product ID // We use filter_var to ensure 'id' is an integer. $product_id = filter_var($_GET['id'], FILTER_SANITIZE_NUMBER_INT); // Validate that the ID is not empty after sanitization if (empty($product_id)) header("Location: products.php?error=invalid_id"); exit(); // (Optional) Check if user is logged in. // If not, you might use $_SESSION['cart'] for guest users. // For this article, we assume a logged-in user. $user_id = $_SESSION['user_id']; // ... Logic continues below
?>
4. Regenerate session ID on cart change (if logged in)
Prevents session fixation when adding items to cart.