Skip to content

Commit 8775523

Browse files
Add workarounds for server-side PHP and Rack
Based on @dezlov and @nanaya feedback from js-cookiegh-70.
1 parent 8a761fe commit 8775523

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

SERVERS.md

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
# Server-side integration
2+
3+
There are some servers that are not compliant with the [RFC 6265](http://tools.ietf.org/html/rfc6265). For those, some characters that are not encoded by js-cookie might be treated differently.
4+
5+
Here we document the most important server-side peculiarities and their workarounds. Feel free to send a [Pull Request](https://github.com/js-cookie/js-cookie/blob/master/CONTRIBUTING.md#pull-requests) if you see something that can be improved.
6+
7+
*Disclaimer: This was built based on community provided information.*
8+
9+
## PHP
10+
11+
In PHP, `setcookie()` function encodes cookie values using `urlencode()` function, which applies `%`-encoding but also encodes spaces as `+` signs, [for historical reasons](http://php.net/manual/en/function.urlencode.php#function.urlencode). When cookies are read back via `$_COOKIE` or `filter_input(INPUT_COOKIE)`, they would go trough a decoding process which decodes `%`-encoded sequences and also converts `+` signs back to spaces. However, the plus (`+`) sign is valid cookie character by itself, which means that libraries that adhere to standards will interpret `+` signs differently to PHP.
12+
13+
This presents two types of problems:
14+
15+
1. PHP writes a cookie via `setcookie()` and all spaces get converted to `+` signs. js-cookie read `+` signs and uses them literally, since it is a valid cookie character.
16+
2. js-cookie writes a cookie with a value that contains `+` signs and stores it as is, since it is a valid cookie character. PHP read a cookie and converts `+` signs to spaces.
17+
18+
To make both PHP and js-cookie play nicely together you need to write custom converters:
19+
20+
```javascript
21+
var Cookies = Cookies.withConverter({
22+
write: function (value) {
23+
// Encode all characters according to the "encodeURIComponent" spec
24+
return encodeURIComponent(value)
25+
// Revert the characters that are unnecessarly encoded but are
26+
// allowed in a cookie value, except for the plus sign (%2B)
27+
.replace(/%(23|24|26|3A|3C|3E|3D|2F|3F|40|5B|5D|5E|60|7B|7D|7C)/g, decodeURIComponent);
28+
},
29+
write: function (value) {
30+
return value
31+
// Decode all characters according to the "encodeURIComponent" spec
32+
.replace(/(%[0-9A-Z]{2})+/g, decodeURIComponent)
33+
// Decode the plus sign to spaces
34+
.replace(/\+/g, ' ')
35+
}
36+
});
37+
```
38+
39+
Rack seems to have [a similar problem](https://github.com/js-cookie/js-cookie/issues/70#issuecomment-132503017).

0 commit comments

Comments
 (0)