So from my understanding of PHP and cookies, if I use the setcookie()
function, then I get a cookie that is automatically url encoded. And when I go to the $_COOKIE
array, I should get the cookie back, automatically url decoded. Problem is, it seems to be decoding the cookie twice when I look in $_COOKIE
.
Say I have a cookie whose value is "Name|ID|Email", for example:
Joe|123|[email protected]
This would be encoded as:
Joe%7C123%7Cmy%2Bemail%40somewhere.com
Notice the plus sign is encoded, so theoretically I ought to get it back if I decode it. Since this is automatically done in $_COOKIE
, I ought to get back what I started with. But instead, I'm getting back:
Joe|123|my [email protected]
Notice the space where the plus used to be. This is what I would expect if I ran an additional urldecode()
on the cookie. But I'm not, so I have no idea why I would be getting a space instead of a plus.
Another interesting twist. A refresh on the page seems to produce the correct output. Any ideas why it's behaving like this?
FYI, to set the initial cookie, I use javascript and escape()
the script to produce the encoded string. Might this be an hand off issue between javascript and PHP?
Thoughts would be appreciated.
It's worth noting that both "%20" and "+" are valid encodings of a space character. Per the Wikipedia article on URL encoding (emphasis added):
When data that has been entered into HTML forms is submitted, the form field names and values are encoded and sent to the server in an HTTP request message using method GET or POST, or, historically, via email. The encoding used by default is based on a very early version of the general URI percent-encoding rules, with a number of modifications such as newline normalization and replacing spaces with "+" instead of "%20". The MIME type of data encoded this way is application/x-www-form-urlencoded, and it is currently defined (still in a very outdated manner) in the HTML and XForms specifications.
More specifically related to PHP and JavaScript, see the top answer on this question: