0

I have a URL which contains a '!' in the value of a query parameter. I enocode the param string in cookies and load a related page. From php:

foreach ( $_GET as $key => $value ){
    setcookie($key,$value,time()+60,'/');
}

In the related page, the value of the cookie (read through javascript/jquery $.cookie("")) has the '!' encoded as %21.

Can someone tell me why the '!' has been encoded? Isn't it a valid character in a cookie value?

LenB
  • 1,126
  • 2
  • 14
  • 31

2 Answers2

0

There are two places that the data may be encoded. The first, is when it is fetched from the $_GET array, the $value may be encoded, and may be decoded by using rawurldecode(). The second place that encoding may occur is when using setcookie(); to avoid this, use setrawcookie() instead, which will set the raw cookie instead of an encoded cookie.

foreach ( $_GET as $key => $value ){
    setrawcookie($key, rawurldecode($value), time() + 60, '/');
}
Andrew
  • 1,322
  • 14
  • 20
0

Can someone tell me why the '!' has been encoded? Isn't it a valid character in a cookie value?

See this answer. According to the the RFC 6265, ! is a valid character in the cookie name and value. If php is encoding ! it means that it is a bug.

To fix this you can do what @Andrew suggested or use a library called js-cookie that allows intercepting the cookie reading using converters, then you can revert the encoding that PHP does in the client.

Community
  • 1
  • 1
Fagner Brack
  • 2,365
  • 4
  • 33
  • 69