Page 1 of 1

Cookies not saving.

Posted: Sun Mar 15, 2009 1:04 pm
by twick100
For whatever reason my Cookies will not save/change values more than once.

Heres some code. I Know I am doing something wrong.

BEFORE my HTML Tag

Code: Select all

<?php
if(!isset($_COOKIE['cart_ID'])) 
{
    setcookie("cart_ID","", time() + 3600); 
}
if(!isset($_COOKIE['cart_Item'])) 
{
    setcookie("cart_Item","", time() + 3600);   
}
if(!isset($_COOKIE['cart_Price'])) 
{
    setcookie("cart_Price","", time() + 3600);  
}
 
?>
When the browser window closes (In this case I am using jQuery thickbox) the cookies go away.

These functions will set a cookie fine but only one, it will not continue to add to the value. Make Sense?

get_product($id) gets product information into an array without a problem.

Code: Select all

    function add($id)
    {
        $product = get_product($id);
        $_COOKIE["cart_ID"] = $_COOKIE["cart_ID"].$id."|";
        $_COOKIE["cart_Item"] = $_COOKIE["cart_Item"].$product[0]."|";
        $_COOKIE["cart_Price"] = $_COOKIE["cart_Price"].$product[1]."|";
        echo "Added ".$product[0]." to your cart!<br />";
        view();
        
    }
    
    function view()
    {
        $ids = explode("|",$_COOKIE["cart_ID"]);
        $items = explode("|",$_COOKIE["cart_Item"]);
        $prices = explode("|",$_COOKIE["cart_Price"]);
        
        $rows= count($ids);
        echo $rows;
        
        $num=0;
        echo "<table border=1px>";
        while($num < $rows)
        {
            echo "<tr>";
            echo "<td>".$items[$num]."</td>";
            echo "<td>".$prices[$num]."</td>";
            echo "</tr>";
            $num++;
            
        }
    }
I am using MAMP as my local server with default settings.
I am not so good at explaining things and a newb to PHP Cookies. Any help is appreciated.
Also, if there is a better way of managing cookie with changing data, please let me know.

Re: Cookies not saving.

Posted: Sun Mar 15, 2009 1:28 pm
by twick100
Thank you for the reply.

I changed it up a little and put the following before the <HTML>.

Code: Select all

<?php
 
    require("include.php");
    add(2);
 
 
    function add($id)
    {
        $product = get_product($id);
        
        setcookie("cart_Item",$_COOKIE["cart_Item"].$product[0]."|");
        setcookie("cart_Price",$_COOKIE["cart_Price"].$product[1]."|");
        
    }
    header("Location:cart.php?action=view");
    
 
?>
I am now getting the following errors.

Warning: Cannot modify header information - headers already sent by (output started at /Applications/MAMP/htdocs/eCommerce/Data/cart.php:14) in /Applications/MAMP/htdocs/eCommerce/Data/cart.php on line 14

EDIT: Line 14 is "setcookie("cart_Item",$_COOKIE["cart_Item"].$product[0]."|");