January 4, 2011

storing multiple values of a variable in cookie and comparing

Question by John

How can i store multiple values for a variable in cookie using php, for example
$id = 1,2,4,5
Then how can i compare the stored values with a variable? for example, $new_id=4, i want to check if $new_id value exists in the stored values of $id in cookie.
Thanks for help and have a nice day.

Answer by tdammers

You can store arbitrary strings in cookie elements, so a serialized array should work. Example:

// To store:
$ids = array(1, 2, 3, 4);
setcookie('ids', serialize($ids));

// To retrieve:
$serialized = $_COOKIE['ids'];
$ids = unserialize($serialized);
// sanity check: $ids needs to be an array.
assert(is_array($ids));

// Now let's check:
if (in_array(4, $ids)) {
    // Yes, it's here.
}

A few caveats though:

  • The cookie is completely in the hands of the client, and cookie values should never be trusted. Treat them just like you would treat query string parameters or POST data.
  • Cookies offer very limited storage (IIRC, the standard gives you 4096 bytes to work with).

With these in mind, it might be a better idea to store the array in $_SESSION instead – this will give you virtually unlimited storage, and the only way for the client application to fiddle with the values is through your code.

Answer by Starx

Store array in cookie and then compare them

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!