Search code examples
phparraysshopping-cartsetcookie

add Variable Array to Cookie then getting error


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

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.