Question

After input some variable,

PHP code:

$CartItem = array(
        'itemID' => $itemID,
        'ProductName' => $ProductName,
        'Option' => $Option,
        'Quantity' => $Quantity,
        'Price' => $Price,
        'Total' => $Total
    );

setcookie('CartItem', $CartItem, null);

Output error:

Warning: setcookie() expects parameter 2 to be string, array given in /Users/user/Sites/app/addtocart.php on line 46
Was it helpful?

Solution

As the error suggests, cookie data must be in string format. More importantly, you shouldn't store real data in a cookie, because the user can edit them.

Since you're using PHP, you can utilize sessions... You can use session_start() which will set a cookie that you don't need to manage, and then you can set data in the $_SESSION variable server-side.

See here: http://php.net/manual/en/function.session-start.php

Note that session_start() must be called before anything is output on each page.

OTHER TIPS

We can add one variable at a time in cokkie so do this

$CartItem[] = array(
        'itemID' => $itemID,
        'ProductName' => $ProductName,
        'Option' => $Option,
        'Quantity' => $Quantity,
        'Price' => $Price,
        'Total' => $Total
    );

foreach($CartItem as $key=>$value)
{
setcookie($key, $value, null);

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top