John
John

Reputation: 423

storing multiple values of a variable in cookie and comparing

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.

Upvotes: 0

Views: 8277

Answers (5)

Zaziffic
Zaziffic

Reputation: 356

Here is one out of many solutions (syntax may contain errors):

// Create an array with the values you want to store in the cookie
$id = array(1, 2, 3, 4);

// Create cookie
set_cookie('id', implode(',', $id));

// Get cookie
$id = explode(',', $_COOKIE['id']);

// Test value
if(in_array($newId, $id) === true) {
  // Value is in the array
}

Restrictions: The values stored in $id cannot include commas, choose another separator if you need to store commas

Upvotes: 0

Starx
Starx

Reputation: 78971

Store array in cookie and then compare them

Upvotes: 0

Uncoke
Uncoke

Reputation: 1902

to use the multiple value you can use the array and then to store it you can serialize ( and unserialize) the array.

To create array: $array = array(1,2,3,4);

To compare: if (in_array(2,$array)) echo "Yep";

To serialize the data to be stored: $store = serialize($array);

Ten you will be able to create the cookie with $store data and then use unserialize($store) to reconvert data in array.

Serialize Manual

Upvotes: 0

tdammers
tdammers

Reputation: 20721

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.

Upvotes: 3

eHussain
eHussain

Reputation: 3357

Try with following snippet.

// do Stuff to retrieve value of $id from cookie.

// explode variable to array
$idArr = explode(',' , $id);

// check existence of new_id in cookie variable.
if(in_array($new_id , $idArr)){

// new_id exist in cookie variable

}

Hope this will help

Thanks!

Hussain.

Upvotes: 0

Related Questions