Avatar of phenixfilms
phenixfilms asked on

multi-dimensional array in php cookie

I'm trying to create a shopping cart whereby a user can add products with information associated, to a cookie.

each time the user adds a new product, the array should incremement.

Product data includes:
strName, strColor, strQty

Code attached doesn't work. Thoughts
$cart = $_COOKIE["cart"];
 
$aOrder = array(
"strName"=>$strName,
"strColor"=>$strColor,
"nQty"=>$nQty);
 
$cart[] = $aOrder;
setcookie("cart",$cart,time()+3600,"/");

Open in new window

E-CommercePHP

Avatar of undefined
Last Comment
Ray Paseur

8/22/2022 - Mon
Ray Paseur

You might want to look at serialize() to convert the data into something that can be stored in a cookie.

Best, ~Ray
GarbsTheTurtle

Your code looks syntactically correct. Can you post a more complete block of code, showing how the snippet above is used?
Ray Paseur

Actually, delete/disregard my earlier post.  This is a quote from the PHP site:

Cookies names can be set as array names and will be available to your PHP scripts as arrays but separate cookies are stored on the users system. Consider explode() to set one cookie with multiple names and values. It is not recommended to use serialize() for this purpose, because it can result in security holes.

Best regards, ~Ray
All of life is about relationships, and EE has made a viirtual community a real community. It lifts everyone's boat
William Peck
ASKER
phenixfilms


#get the cart contents
$cart = $_COOKIE["cart"];
print "Opening Cart Contents:";
print_r($checkcart);
print "<br><Br><Br> ";

#pretend that i'm adding a product...
$aOrder = array(
"strName"=>"hello product 1",
"strColor"=>"red",
"nQty"=>"1");

$cart[] = $aOrder;


# this accuratly shows the above array.
print_r($cart);


# here i'm setting my cart to the cookie...
setcookie("cart",$cart,time()+3600,"/");


#what's in my cart?
$checkcart = $_COOKIE["cart"];

print "<br><Br><Br> New Cart:";

# returns nothings???????
print_r($checkcart);
GarbsTheTurtle

Updated data in $_COOKIE is not available until the next page load. Does your $_COOKIE data look right if you reload your page?

http://us3.php.net/setcookie
Ray Paseur

Cookies are ONLY available to the scripts that run AFTER they have been set.  In other words, the $_COOKIE array is populated once at the start of your script.  You can set more cookies, but they are not available in $_COOKIE until you close out your script and start a new script.
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
Ray Paseur

I have never tried it, but what do you suppose would happen if you did this...

It might give you an easy work-around, but it does not seem like good code design and should not be part of your long-term solution.

HTH, ~Ray
$_COOKIE["testData"] = "Hello World!";
var_dump($_COOKIE);

Open in new window

ASKER
phenixfilms

Yes, to the "they are only available at reload" yet, for some reason even if you reload, they are not available. The array they prints out is always the same as per my modded code below. So every time the page reloads it is supposed to append another item to the array and then that should be available in the cookie....

It always just sets one item.

#get the cart contents
$cart = $_COOKIE["cart"];
print "Opening Cart Contents:";
print_r($cart);
print "<br><Br><Br> ";

#pretend that i'm adding a product...
$aOrder = array(
"strName"=>"hello product 1",
"strColor"=>"red",
"nQty"=>"1");

$cart[] = $aOrder;


# this accuratly shows the above array.
print_r($cart);


# here i'm setting my cart to the cookie...
setcookie("cart",$cart,time()+3600,"/");



print "<br><Br><Br> New Cart:";

# returns same array as above even after refresh???????
print_r($cart);
Ray Paseur

I think we would need to have the whole script to understand what is going on.  Please post that in the code snippet.

You cannot set a cookie if you have already sent any data, including whitespace, to the browser.

Standing by, ~Ray
Experts Exchange is like having an extremely knowledgeable team sitting and waiting for your call. Couldn't do my job half as well as I do without it!
James Murphy
ASKER
phenixfilms

the above was the whole script... i've modified it to not print out the text until after the cookie... i've also included the html form i'm using to submit the product information now...
<form method="post" action="test.php">
	Name: <input type="text" id="" name="strName"/><Br/>
	Color: <input type="text" id="" name="strColor"/><Br/>
	Qty <input type="text" id="" name="nQty"/><Br/>
	<input type="submit" />
  </form>
 
 
 
<?
 
#get the cart contents
$cart = $_COOKIE["cart"];
 
#pretend that i'm adding a product... 
$aOrder = array(
"strName"=>"$strName",
"strColor"=>"$strColor",
"nQty"=>"$nQty");
 
$cart[] = $aOrder;
 
# here i'm setting my cart to the cookie...
setcookie("cart",$cart,time()+3600,"/");
 
# returns same array as above even after refresh???????
print_r($cart);
 
?>
<a href="additem.html">Add/Append Another Item To Cart</a>

Open in new window

Ray Paseur

Thanks, I'll run that and see what I can find.  Back in a moment, ~Ray
Ray Paseur

While I am looking at this, please read the man page here.
http://us2.php.net/manual/en/function.setcookie.php

There may be a way around it, but the design appears to be flawed.
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
Ray Paseur

Output contains this...  I put some whitespace around the code I changed in your script.

Warning: setcookie() expects parameter 2 to be string, array given in /home/websitet/public_html/RAY_temp_phenixfilms.php on line 27

SETCOOKIE FAILED
<form method="post" action="test.php">
        Name: <input type="text" id="" name="strName"/><Br/>
        Color: <input type="text" id="" name="strColor"/><Br/>
        Qty <input type="text" id="" name="nQty"/><Br/>
        <input type="submit" />
  </form>
 
 
 
<?php
 
 
 
// MAKE SURE WE SEE ERRORS
error_reporting(E_ALL);
 
 
 
 
 
 
#get the cart contents
$cart = $_COOKIE["cart"];
 
#pretend that i'm adding a product...
$aOrder = array(
"strName"=>"$strName",
"strColor"=>"$strColor",
"nQty"=>"$nQty");
 
$cart[] = $aOrder;
 
# here i'm setting my cart to the cookie...
 
 
 
 
 
// TEST TO SEE IF THE setcookie() FUNCTION WORKED
if (!setcookie("cart",$cart,time()+3600,"/"))
{
	echo "<br/>SETCOOKIE FAILED \n";
}
 
 
 
 
# returns same array as above even after refresh???????
print_r($cart);
 
?>
<a href="additem.html">Add/Append Another Item To Cart</a>

Open in new window

Ray Paseur

As I'm thinking about this, I can think of two ways to do what you want.  One is to ignore the warning from PHP and use serialize() to make a string.  The other is to store the array (serialized) into a data base table of field type=TEXT and store a key set to md5(serialize($cart)).  Use the MD5 key as the cookie value.  When you retrieve the cookie, go to the data base and retrieve the serialized array, then unserialize it and carry forth.

HTH, ~Ray
ASKER
phenixfilms

So I can't put an array into the cookie??
This is the best money I have ever spent. I cannot not tell you how many times these folks have saved my bacon. I learn so much from the contributors.
rwheeler23
ASKER
phenixfilms

Could I not save the serialized value into the cookie?
ASKER CERTIFIED SOLUTION
Ray Paseur

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
See how we're fighting big data
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
SOLUTION
Log in to continue reading
Log In
Sign up - Free for 7 days
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
Ray Paseur

Notwithstanding that "piranha" is a bit of a prick, there may be some helpful information on this page:
http://www.phpbuilder.com/board/showthread.php?threadid=10346979

I think the central issue with holding cart data in the session instead of the data base goes to whether a client should be allowed to put something in his cart, close the browser, come back later and find the cart still has his item(s).  Most carts seem to be able to remember what I'm shopping for, and that means they would be using a persistent stateful element, such as a data base, to store my cart.