For a basic PHP cart, keep product IDs and quantities in $_SESSION['cart'], then look up product details and calculate prices from your server-side catalog. Start the session before accessing it, accept cart changes only through validated POST requests, and recheck prices and stock at checkout.
Store cart items in a PHP session
PHP sessions let an application preserve data across requests. Call session_start() before reading or writing $_SESSION, then use stable product IDs as keys and integer quantities as values. See the PHP Sessions manual.
<?php
session_start();
$_SESSION['cart'] ??= [];
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$id = filter_input(INPUT_POST, 'product_id', FILTER_VALIDATE_INT);
$qty = filter_input(INPUT_POST, 'quantity', FILTER_VALIDATE_INT);
if ($id === false || $id === null || $qty === false || $qty < 1) {
http_response_code(400);
exit('Invalid cart input');
}
// Confirm the product exists and enforce a maximum quantity here.
$_SESSION['cart'][$id] = ($_SESSION['cart'][$id] ?? 0) + $qty;
header('Location: cart.php', true, 303);
exit;
}
This example adds a submitted quantity to the existing quantity and redirects to the cart page after a successful POST. It is a starting point, not a complete production handler: validate the product against your server-side catalog and impose a quantity limit before changing the session.
Render products and calculate totals from trusted data
The session should hold identifiers and quantities, not prices supplied by the browser. For each cart entry, load the current product record from your catalog, display its name and price, and calculate the line total on the server. Use integer minor units, such as cents, or another decimal-safe money strategy rather than relying on binary floating-point arithmetic for currency.
#1 Best Overall
For example, if a product costs 1,299 cents and the cart contains two, its line total is 2,598 cents. Add those integer line totals to produce the subtotal; calculate tax, shipping, and any discount according to your application’s rules. Do not trust a submitted total or price, even if it is hidden in a form field.
Update quantities and remove items
Use separate POST actions, or a single handler with an explicit action field, for quantity changes and removals. Validate the action, product ID, and quantity on the server for every request. A practical policy is to reject quantities below one and above your chosen maximum; treat a removal as a distinct action that unsets the product ID from $_SESSION['cart'].
Rank #2
Protect each mutation with a CSRF token. A session keeps cart state, but it does not prove that a request to change that state was intentionally submitted by your site’s user. Apply CSRF protection to add, update, remove, and checkout forms, and verify authorization where an operation depends on a signed-in customer.
Recheck the cart during checkout
A cart may remain in a session while catalog data changes. Before accepting an order, reload product records and check that each item still exists, is available, and has a current price. Recalculate tax, shipping, and promotions using the rules that apply at checkout, then show the customer the resulting order total before final submission.
Quick wins for a faster PC:
Scan for outdated or missing drivers - takes under a minuteDriver Scan →Repair Windows errors before they cause bigger problemsFix Now →Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →Define how your application handles unavailable items or changed prices: for example, flag the affected line and ask the customer to review it rather than silently charging an outdated amount. The correct policy depends on your store’s business rules.
Secure and manage PHP sessions
Use HTTPS and configure session cookies with HttpOnly, Secure when the site requires HTTPS, and an appropriate SameSite setting such as Lax or Strict. PHP’s session security guidance covers session configuration and handling in its session security ini settings and session security manual.
Rank #4
Avoid putting session IDs in URLs. URL-carried IDs can be exposed through links, referrer logs, browser history, or search engines. Regenerate the session ID at sensitive transitions, such as when a user signs in, following PHP’s session_regenerate_id() guidance.
PHP sessions can hold a session lock while a request works with session data. Keep that work brief and, when it is safe for the rest of the request, close the session after writing so other requests from the same user are not unnecessarily held up. Follow PHP’s session_write_close() documentation for the function’s behavior.
Free tools Windows power users keep installed
One-click scans. No signup required.
Choose session storage or a database cart
| Approach | Useful when | Trade-off |
|---|---|---|
| Session-only cart | You need a straightforward cart tied to the visitor’s active session. | It does not inherently provide a cart that follows a signed-in customer across devices or supports recovery after a session ends. |
| Database-backed cart | You need persistent carts associated with customer accounts, or your application needs active-session tracking. | You must design and maintain cart records and decide how to reconcile them with an anonymous session cart. |
For a signed-in customer, decide whether to merge an anonymous session cart into the saved cart at login. Specify how you handle duplicate products, quantity limits, and items that are no longer available. PHP’s session documentation discusses database-backed designs for applications that need active-session tracking; it does not prescribe a particular cart-merging policy.
Choose a handler style and interaction pattern
Procedural handler or Cart class
A small procedural handler can be enough for a simple site. As cart rules grow, a Cart class can group operations such as adding, updating, removing, and calculating totals, making those rules easier to organize and test. Whichever style you choose, keep validation and price lookup on the server.
Standard form posts or AJAX
Ordinary HTML forms are the simpler choice: the browser submits a POST, PHP updates the session, and the server redirects back to the cart. AJAX can update the page without a full reload, but it adds client-side request handling and does not change the security requirements. AJAX mutations still need server-side validation, CSRF protection, and trusted price calculations.
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.
The Tool Desk
Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →Outbyte Driver Updater FREEScan for outdated or missing drivers - takes under a minuteDriver Scan →

