Skip to content

Instantly share code, notes, and snippets.

/cart.php Secret

Created August 23, 2016 06:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/fb3976461906ecc05098aacce98116e4 to your computer and use it in GitHub Desktop.
Save anonymous/fb3976461906ecc05098aacce98116e4 to your computer and use it in GitHub Desktop.
<?php
session_start();
$products = [];
$products[1] = array('name' => 'Bar Soap', 'price' => '4.50', 'weight' => '4');
$products[2] = array('name' => 'Lotion', 'price' => '9.99', 'weight' => '8');
$products[3] = array('name' => 'Liquid Soap', 'price' => '12.00', 'weight' => '10');
function product_exists($product_id) {
global $products;
return array_key_exists($product_id, $products);
}
function product_in_cart($product_id) {
return array_key_exists($product_id, $_SESSION['cart']);
}
$product_id = $_GET['product_id']; //the product id from the URL
$action = $_GET['action']; //the action from the URL
switch ($action) {
case 'add':
if (product_exists($product_id)) {
if (!isset($_SESSION['cart'][$product_id])){
$_SESSION['cart'][$product_id] = 0;
}
$_SESSION['cart'][$product_id]++;
}
break;
case 'update':
$quantity_array = $_POST['quantity'];
if (isset($quantity_array) && is_array($quantity_array)) {
foreach($quantity_array as $product_id => $quantity) {
if (product_exists($product_id) && product_in_cart($product_id)) {
$_SESSION['cart'][$product_id] = $quantity;
}
}
}
break;
case 'remove':
unset($_SESSION['cart'][$product_id]);
break;
case 'empty':
unset($_SESSION['cart']);
break;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment