Cookies/Accessing A Cookie
Direct HTTP programming (server side)
You have to parse the headers sent by the client, and to check for set-cookie headers. Remember, HTTP protocol is not case-sensitive!
PHP
Use the $_COOKIE superglobal to read the cookies. Remember it can't be used to set or delete cookies, only to read them, though PHP won't shout at you if you try and set some values. Just, it won't give a damn and never set them client-side.
<syntaxhighlight lang="php"> $lover = $_COOKIE['my_lover']; </syntaxhighlight> |
Javascript
Cookies not marked with HttpOnly can be accessed through Javascript. To read them, you have to split the document.cookie string by ';' (alert it just to take a look!) and to split each resulting key=value pair by '='.
<syntaxhighlight lang="javascript"> var cookies = document.cookie.split(';'); var c = new Array(); for (cookie in cookies) { var cs = cookie.split('='); c[cs[0]] = decodeURIComponent(cs[1]); } alert(cs['my_lover']); </syntaxhighlight> |