Stefan Weiss
3/12/2016 3:20:00 PM
On 03/12/2016 14:38, bit-naughty@hotmail.com wrote:
> Is there any difference between the 2, as in one set by JS on the
> browser side, and one set in PHP code running on the server? They both
> result in exactly the same thing happening, right? (ie. for PHP the
> required data just travels over HTTP to the browser, which then does
> whatever?)
Normally, there is no difference. You can read and set cookies on the
server and on the client (with JS).
The situation changes when the cookie set by the server uses the
HttpOnly flag. If the browser supports this extension (and all major
browsers do), they will not let scripting languages read or change the
value of that cookie. See example below.
> If, for example I set "x=3" in a cookie in JS, can I then set "x=4"
> in PHP on the server side? Or even just check what "x" is? How?
Server-side code (PHP):
setcookie("one", "1");
setcookie("two", "2", 0, "", "", false, true); // HttpOnly
setcookie("three", "3");
HTTP response header:
Set-Cookie: one=1
Set-Cookie: two=2; httponly
Set-Cookie: three=3
Client (JS):
console.log(document.cookie); // "one=1; three=3"
document.cookie = "one=11";
console.log(document.cookie); // "one=11; three=3"
document.cookie = "two=22";
console.log(document.cookie); // "one=11; three=3" (!!)
document.cookie = "three=33";
console.log(document.cookie); // "one=11; three=33"
Next HTTP request header:
Cookie: one=11; two=2; three=33
Server-side code (PHP):
var_export($_COOKIE);
// array (
// 'one' => '11',
// 'two' => '2',
// 'three' => '33',
// )
Note that the client was unable to see or modify the value of the "two"
cookie because it was protected by the HttpOnly flag.
- stefan