Joshua Neve
Joshua Neve

Reputation: 13

Check to see if a cookie exists based on part of its name in PHP

I have set a cookie. I want to add multiple cookies, one for each item and have the quantity of these items in each of the values (this is a shopping cart). My problem is, how do I (for example) check to see how many items there are based on the cookie names. I can'y just count ALL cookies because I have cookies being used for other purposes too.

You can see how I have set them - this might provide a bit of clarity. I can confirm the cookie does set as I intended it to. I just don't know where to start when trying to identify these cookies by name.

if (!isset($_COOKIE['cart_item_' . $_GET['itemadd']])){

//if cookie doesn't, create one
setcookie($cookie_name, "1", time() + 86400, "/");
//echo "did i get here";
}else{
    //if cookie does, add to quantity
    if (!isset($_GET['quantity'])){
        $cookie_value = $_COOKIE['cart_item_' . $_GET['itemadd']] + 1;

    }else{
        $cookie_value = $_GET['quantity'];  //cookie value is the number of items being added
        }
        //echo "CN:" . $cookie_name . " - CV:" . $cookie_value;
    setcookie($cookie_name, $cookie_value, time() + (86400), "/"); // 86400 = 1 day

Upvotes: 1

Views: 189

Answers (1)

Waseel Ahmad Mufti
Waseel Ahmad Mufti

Reputation: 170

You can use Session for shopping cart. I hope the following code will help you:

if(!isset($_SESSION['some_product_id'])){
   $data = array(
              'product_name' => 'some product name',
              'quantity' => 5, //some quantity,
              'other_things' => 'Some other values',
        );
    $_SESSION['some_product_id'] = $data;
}else{
      echo 'Product Name: '. $_SESSION['some_product_id']['product_name'] . '<br>';
      echo 'Product Quantity: '. $_SESSION['some_product_id']['quantity'] . '<br>';
      echo 'other_things: '. $_SESSION['some_product_id']['other_things'] . '<br>';
}

Upvotes: 1

Related Questions