hi everybody
i am stuck in a problem please help!
i am making a shopping cart, in which, the items selected (added to cart) are stored in an array and then that array is stored in a cookie.
The id is stored in an array after the user clicks add to cart button.
The code first checks whether cookie exists or not, if yes then it copies the item from the older array into a new array and adds newly added item selected (added to the cart) by the user to the array, Then that array is again written to the cookie.
Now everything works fine but in my code i am not able to get the updated cookie content until i close my browser and open again and add another item.
supposigly i added an item whose id is: 2, now when the user clicks on add to cart button, the code writes a cookie with the relevant id selected but it does not displays the id until i add another item or re-start the browser or refresh the page.
if i refresh the page then the same id is added twice to the cookie.
i am writing my code below.
//////////////////////////////////////////////////////////////////////////////////////////////////
<?php
if(isset($COOKIE['check']))
{
$arr = stripslashes($COOKIE['check']);//get array from the cookie.
$arr = unserialize($arr);//unserialize to get number of values and array values.
$num = count($arr);//count number of elements in the array if the cookie is set.
//declare a new array to store updated items (added to the cart)
$count = 0;
$new_array = array();
//copy the items from old array to the new array
foreach ($arr as $value)
{
$new_array[$count] = $value;
$count++;
}
//insert newly added item to the new array and set the cookie with the new updatd array.
$new_array[$count] = $POST['sel_item_id'];
$cookie = serialize($new_array);//serialize before setting cookie.
$val = setcookie('check',$cookie, time() + 3110400);
if($val == TRUE)
echo "cookie set<br>";
}
else
{//set the initial cookie if the cookie is not set yet.
$id = $POST['sel_item_id'];
$cookie = serialize(array($id));
$val = setcookie('check',$cookie,time()+3110400);
if($val == TRUE)
echo "Welcome to our shop";
}
//this if block displays the item id values that have been written to the cookie
I DO NOT GET THE UPDATED COOKIE VALUE IN THE IF BLOCK GIVEN BELOW UNTILL I RESTART THE BROWSER, REFRESH OR ADD ANOTHER ITEM.
if(isset($COOKIE['check']))
{
$arr = stripslashes($COOKIE['check']);
$arr = unserialize($arr);//unserialize to get number of values and array values.
$num = count($arr);//count number of elements in the array if the cookie is set.
echo "total items $num<br>";
foreach ($arr as $value)
{
echo "value: $value<br>";
}
}
Please help.
Thanx and regards.
Gaurav Behl.