Questions about this topic? Sign up to ask in the talk tab.

Cookies/Setting A Cookie

From NetSec
Jump to: navigation, search

Direct HTTP programming

Send the Set-Cookie header as many times as there are cookies.

Format:

<syntaxhighlight lang="bash"> Set-Cookie: cookie_name_urlencoded=cookie_value_urlencoded; Expires=Wdy, DD-Mon-YYYY HH:MM:SS GMT; OtherFlags </syntaxhighlight>

For the "OtherFlags", see the Flags section.

PHP (server side)

Savitri says
Note that, since cookies are set in the HTTP headers, they shall be set before the HTML (or whatever you transmit over HTTP) output starts.

See PHP.net. Basically,

<syntaxhighlight lang="php"> //setcookie ( string $name [, string $value [, int $expire = 0 [, string $path [, string $domain [, bool $secure = false [, bool $httponly = false ]]]]]] )

setcookie('my_lover', 'hero hitler (or was it Mr. #?)', time()+1800, '/', '.staff.blackhatacademy.org', false, false); // the false, false at the end is not mandatory, since these parameters are marked as optional. // $value is to be set to the desired value. Note that you shall not use booleans, as setting $value to false will delete the cookie // $expire is the timestamp at which this cookie shall expire // $domain sets the Domain flag (see Flags section // $secure sets the Secure flag (see Flags section // $httponly sets the HttpOnly flag (see Flags section </syntaxhighlight>

Savitri says
Note that PHP takes care of encoding and crap for you, so don't bother with that

Javascript (client side)

To set a cookie, you need to set a properly formatted string to the document.cookie string. Automagically, your browser will add the cookie in the site's jar. You may add all the parameters we describe in here

In order to get the properly formatted string, best option is to use a Date object, which has a very practical toGMTString() method. See this sample

<syntaxhighlight lang="javascript"> // set a cookie that will expire in 30 minutes (1800 seconds), // limited to domains under .staff.blackhatacademy.org // to be transmitted over HTTP // or HTTPS, it doesn't matter to us. var d = new Date(); var expires = new Date(d.getTime()+1800).toGMTString(); document.cookie = "my_lover="+encodeURIComponent("hero hitler in love, or was it Mr #?")+";Expires="+expires+";Domain=.staff.blackhatacademy.org"; </syntaxhighlight>

Feel free to expand this example, put it in a nicely wrapped function, to parameterize it, and whatnot.