Forum Moderators: coopster

Message Too Old, No Replies

setting two cookies

         

sebbothebutcher

7:10 pm on Oct 5, 2004 (gmt 0)

10+ Year Member



hi! i've got a question! i've got a page where a user can login and i want that page to create two cookies, one containing the md5()'ed password, the other one containing the username...
originally, i wanted to have one cookie storing those 2 values by putting an array into it as the cookie value, but php said that only strings were allowed!
now i try to set too cookies at one like this:

setcookie("cookie1",$value1);
setcookie("cookie2",$value2);

but it doesn't work (guess it's because header informations are already sent after setting the first cookie, but it doesn't show any warning similar to that)... only cookie1 is set, but not cookie2!
can anybody help me out?
thanks

jusdrum

8:10 pm on Oct 5, 2004 (gmt 0)

10+ Year Member



You can set multiple values in a cookie like this:

setcookie("mycookie[name1]",$value1);
setcookie("mycookie[name2]",$value2);

Then to access the cookie:

$name1 = $_COOKIE['mycookie']['name1'];

or loop through it:

foreach ($_COOKIE['mycookie'] as $Name => $Value)
{
$$Name = $Value;
}

Hanu

8:47 pm on Oct 5, 2004 (gmt 0)

10+ Year Member



jusdrum's solution is equivalent to your approach, except more difficult. It also sets two separate cookies on the client side. I don't see why your solution doesn't work, though. If the two lines with setcookie() calls are really one behind the other, it should work. The only case in which setting two cookies doesn't work is when you have output statements like echo in between the first and the second call. You have three options:

1) Avoid any output statements before setting the second cookie.

2) Use output buffering as described here [de.php.net]:

Cookies are part of the HTTP header, so setcookie() must be called before any output is sent to the browser. This is the same limitation that header() has. You can use the output buffering functions to delay the script output until you have decided whether or not to set any cookies or send any headers.

3) Store both values in an array and store the serialized array in the cookie as mentioned on this [de3.php.net] page:

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() or serialize() to set one cookie with multiple names and values.

$value = array( $value1, $value2 );
setcookie( "mycookie", serialize( $value ) );

and then

$value = unserialize( $_COOKIE['mycookie'] );
echo $value[0];
echo $value[1];