How do you set a php cookie with multiple values?
If you're only looking to store two values, it may just be easier to concatenate them and store it as such:
setcookie("acookie", $username . "," . $userid);
And to retrieve the information later,
if(isset($_COOKIE["acookie"])){
$pieces = explode(",", $_COOKIE["acookie"]);
$username = $pieces[0];
$userid = $pieces[1];
}
Cheers,
~Berserkguard
<?php
// set the cookies
setcookie("cookie[three]", "cookiethree");
setcookie("cookie[two]", "cookietwo");
setcookie("cookie[one]", "cookieone");
// after the page reloads, print them out
if (isset($_COOKIE['cookie'])) {
foreach ($_COOKIE['cookie'] as $name => $value) {
$name = htmlspecialchars($name);
$value = htmlspecialchars($value);
echo "$name : $value <br />\n";
}
}
?>
http://php.net/manual/en/function.setcookie.php
You can use an array for example
<?php
// the array that will be used
// in the example
$array = array(
'name1' => 'value1',
'name2' => 'value2',
'name3' => 'value3'
);
// build the cookie from an array into
// one single string
function build_cookie($var_array) {
$out = '';
if (is_array($var_array)) {
foreach ($var_array as $index => $data) {
$out .= ($data != "") ? $index . "=" . $data . "|" : "";
}
}
return rtrim($out, "|");
}
// make the func to break the cookie
// down into an array
function break_cookie($cookie_string) {
$array = explode("|", $cookie_string);
foreach ($array as $i => $stuff) {
$stuff = explode("=", $stuff);
$array[$stuff[0]] = $stuff[1];
unset($array[$i]);
}
return $array;
}
// then set the cookie once the array
// has been through build_cookie func
$cookie_value = build_cookie($array);
setcookie('cookie_name', $cookie_value, time() + (86400 * 30), "/");
// get array from cookie by using the
// break_cookie func
if (isset($_COOKIE['cookie_name'])) {
$new_array = break_cookie($_COOKIE['cookie_name']);
var_dump($new_array);
}
?>
Hope this answer help you out