I want to create a php cookie that stores the username and the userid. Or is it better to just use one to get the other?
You can use an array for example
'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