Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store an array into a cookie?

How do you store a multi-array type of data into a cookie.

For example: [[1, 'foo'], [2, 'bar'], [3, 'foobar']]

I can get it to work with a single dimensional array as such:

cookies[:foobar] = { :value => cookies[:foobar] << ",1" }

and then do

cookies[:foobar].split(',').include?("1")

To verify that 1 exists inside the cookie. Not too sure how I can get around this with a multidimensional array

like image 737
Christian Fazzini Avatar asked Jan 07 '12 16:01

Christian Fazzini


People also ask

How do you store an array in cookies?

Example - store array in a cookie: var arr = ['foo', 'bar', 'baz']; var json_str = JSON. stringify(arr); createCookie('mycookie', json_str);

Can a cookie hold an array?

Cookies can hold only strings. If you want to simulate an array you need to serialize it and deserialize it.

Can we store array in cookie in PHP?

Cookies are basically text, so you can store an array by encoding it as a JSON string (see json_encode ). Be aware that there is a limit on the length of the string you can store though.

How do you save something in cookies?

Store objects in the Cookies The cookies store information in the string format only. If users want to store any other types of data in the cookies, they need to convert it to the string using the stringify() method. In this section, we will convert the object to a string and store it in cookies.


2 Answers

Serialize array into json and store to cookies.

Look at two methods:

ActiveSupport::JSON.encode(object)
ActiveSupport::JSON.decode(string)
like image 125
4ndrew Avatar answered Oct 03 '22 16:10

4ndrew


The easiest is probably to use one of the serialisation methods rails/ruby provides such as YAML, marshalling or json.

like image 43
Frederick Cheung Avatar answered Oct 03 '22 15:10

Frederick Cheung