PHP Script for updating Shopping Cart

Current backend pattern: validate input and return JSON

The cart-update endpoint should accept only validated integer IDs and quantities, update the session, and return a predictable JSON response. Product prices should always come from the database later, not from the request.

<?php
session_start();
header('Content-Type: application/json; charset=utf-8');

$productId = filter_input(INPUT_POST, 'p_id', FILTER_VALIDATE_INT);
$quantity = filter_input(INPUT_POST, 'qty', FILTER_VALIDATE_INT);

if ($productId === false || $productId === null || $quantity === false || $quantity === null) {
    http_response_code(422);
    echo json_encode(['ok' => false, 'message' => 'Invalid product or quantity.']);
    exit;
}

$quantity = max(0, min(10, $quantity));
$_SESSION['cart'] = (isset($_SESSION['cart']) && is_array($_SESSION['cart'])) ? $_SESSION['cart'] : [];

if ($quantity === 0) {
    unset($_SESSION['cart'][$productId]);
} else {
    $_SESSION['cart'][$productId] = $quantity;
}

echo json_encode([
    'ok' => true,
    'size_of_cart' => count($_SESSION['cart'])
]);
?>

For a real shop, also add CSRF protection, authentication where appropriate, stock checks, and server-side checkout validation.

We update the session variable $_SESSION['cart'] using PHP script. This page ( add.php ) will receive product_id and quantity against each product and update the cart.
DEMO : Shopping Cart Script with Add remove products

add.php The backend PHP script

The PHP code inside add.php first receive the data Product id (p_id) and quantity ( qty ) from front end script.
$p_id=$_POST['p_id'];
$qty=$_POST['qty'];
Data validation is done by setting Flags
$elements=array("msg"=>"","size_of_cart"=>"0","validation_status"=>"T");

if(!is_numeric($p_id)){$elements['validation_status']="F";
$elements['msg'].="Data Error";}
if(!is_numeric($qty)){$elements['validation_status']="F"; 
$elements['msg'].="Data Error";}
If the validation is cleared then Session status is checked, if it is not there then new session is created.
if($elements['validation_status']=='T'){

if(isset($_SESSION['cart']) && !empty($_SESSION['cart'])) {
	//echo " session  is available ";

}else{
	//echo " session is not available ";
	$_SESSION['cart']=array();
}
....
....
}
If the product id is already there then the product is removed first.
foreach ($_SESSION['cart'] as $key => $val) {
if($p_id=== $_SESSION['cart'][$key]['p_id']){
	unset($_SESSION['cart'][$key]); // Remove the product
}
}
If quantity is not equal to zero then add the product with new quantity.
if($qty !=0){
$b=array("p_id"=>"$p_id","qty"=>$qty);
array_push($_SESSION['cart'],$b); // Items added to cart
$elements['msg'].="Product Added : p_id: $p_id , qty = $qty ";
}else{
$elements['msg'].="Product Removed : p_id: $p_id   ";	
}
We need to find out the total number of products in the cart after all above transactions are completed. This data we will send to front end script as we have to update the data at top right side of the page.
$elements['size_of_cart']=sizeof($_SESSION['cart']);
At the end we will send the JSON output to our front end script.
echo json_encode($elements);
plus2-cart-v1: Shopping Cart Script Display cart Products


Subscribe to our YouTube Channel here



plus2net.com











PHP video Tutorials
✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer