set cookie with 3 values, and then extract the 3 values when reading

179 views Asked by At

im working on a remember me function and need to do e.g:

setcookie(
    "cookie",
"$userid, $token, $date",
time() + (10 * 365 * 24 * 60 * 60)
);

I then want to be able to read the cookie and assign each value to a php variables:

$user id =
$token =
$date =

Any help? i have found a few examples but they dont work.

P.S. Ignore the lack of security. Im making this work and then creating all the hashing etc later.

EDIT:

Found this:

setcookie("acookie", $username . "," . $userid);

But cant get it working with a 3rd variable

2

There are 2 answers

0
display-name-is-missing On BEST ANSWER

Solution 1

You could do something like this (if you really want just one cookie):

$cookie_val = $userid . ':' . $token . ':' . $date; 
// Make sure the values don't contain ":" or change to other 
// character that the values don't contain

setcookie("acookie", $cookie_val, time() + (10 * 365 * 24 * 60 * 60));

Then, on the page where you're checking the cookie values, you could do this:

$cookie_arr = explode(':', $_COOKIE['acookie']);

$user id = $cookie_arr[0];
$token = $cookie_arr[1];
$date = $cookie_arr[2];

Solution 2

This solution is much easier and I recommend that you use this. Just make three cookies, like $_COOKIE['user_id'], $_COOKIE['token'] and $_COOKIE['date'] and then call them simply by those names when you need to check their values.

// Create cookie
setcookie("user_id", $user_id, time() + (10 * 365 * 24 * 60 * 60));

// Check cookie
$user_id = $_COOKIE['user_id'];

And so on...

0
Zarathuztra On

As far as your cookies go, once they are set appropriately you can access them via the $_COOKIE superglobal, similar to how you would use $_GET and/or $_POST.