Question: How do I read a cookie with a given name?
Answer: Here is a function for reading a cookie
that has been set by
. It relies on the standard string manipulation methods:
A note on reliability: Why did we need to prefix the cookie with a space (
) or a semicolon (
) in the beginning of the function? Here is why: to avoid false matches. Assume that we succefully created one cookie named
. Now try reading some
... These other cookies presumably do not exist; however, a buggy version of
without the highlighted safeguards would still return a non-empty value (most likely, the same value as for
as if all of the above cookies were present! We thus see that there are important special cases where a quick-and-dirty reader function may easily fail.
Difficult special cases like this manifest themselves especially when there are two or more semicolon-separated cookies in the
and that's exactly what may happen on big websites in real life. What if we must read not only cookies set by our own scripts, but also those cookies that came from various server-side applications? Let us consider
examples that we might want to handle with our cookie-reader function.
name1=value1; name2=value2; name3=value3; name4=value4; . . . //an easy case
Here are the pitfalls:
Just_a_value; name2=name1=a&b=c; name1=value1; e1=v1; e2=v2; //more difficult
argument may hold a substring of some other existing cookie name(s)
may hold a substring of another cookie's value
may or may not have the
Next, we'll write another function for reading a cookie using regular expressions. As you will see, the
-based version turns out to be shorter and easier to modify, but somewhat less readable. Please read on...