I have a shopping cart which I store in a cookie. The cookie 'shopping_cart' is set once an item is added onto the cart.
function shopping_cart_add(){
if(isset($_COOKIE['shopping_cart'])){
$cookie_data = $_COOKIE['shopping_cart'];
$cart_data = json_decode($cookie_data, true);
}else{
$cart_data = array();
}
$data = array(
"cart_id" => 1,
"product_id" => $this->input->post('product_id'),
"product_name" => $this->input->post('product_name'),
"product_price" => $this->input->post('product_price'),
"quantity" => $this->input->post('quantity'),
"options" => $this->input->post('options'),
"description" => $this->input->post('description'),
"image" => $this->input->post('image')
);
$cart_data[] = $data;
$item_data = json_encode($cart_data);
setcookie('shopping_cart',$item_data,time() + (86400 * 30));
$_COOKIE['shopping_cart'] = $item_data;
}
I am having a problem with when the user wants to remove an item from cart. I am using codeigniter framework but not its inbuilt cookies.
The following is the code in my view for deleting an item:
<td><a href="<?php echo base_url('designs/delete/');?><?=$values['product_id'];?>" type="button" class="btn btn-default btn-sm">Delete</a></td>
The following is the code in my controller for deleting an item:
function delete($delete_id){
$cookie_data = $_COOKIE['shopping_cart'];
$cart_data = json_decode($cookie_data, true);
foreach ($cart_data as $key => $value) {
if ($cart_data[$key]['product_id'] == $delete_id) {
unset($cart_data[$key]);
$item_data = json_encode($cart_data);
setcookie('shopping_cart',$item_data,time() + (86400 * 30));
header("location:/category/cart_summary.php?remove=1");
}
}
}
However I keep getting an error when I click the delete button.
Undefined variable $_COOKIE['shopping_cart']
Yet when I check my browser it show the cookie exists. What could be the problem?? I have already checked similar questions on stack pertaining to this issue but none has helped. This includes: undefined index for cookie in some browsers PHP Undefined Index When Checking Cookie Value And Cookie Exists
This probably happens because you didn't explicitly mentions on what path the shopping_cart
cookies will be saved. Try to add a 4th parameter (path) at each setcookie
:
setcookie('shopping_cart',$item_data,time() + (86400 * 30), '/');
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.