It's perhaps common knowledge these days as to what a cookie is. A cookie sits client-side in a user's browser and is sent to the server when the page is loaded. Cookies, however, can go a little deeper than just setting and receiving.
setcookie('myCookie', 'TalkPHP.com', time() + 2592000);
function accepts a total of 7 arguments. The first 2 are the only mandatory arguments. The above code probably looks familiar - we give the cookie a name, give it a value and set its duration to 30 days. The 3rd argument, the time argument, will default to 0 if you leave it empty and thus the cookie will expire at the end of the session - typically when the user closes their browser.
The 4th argument in
is the cookie path. By default, if you leave this argument empty, it will set itself as the directory you are currently in. For instance, if I'm in the directory TalkPHP.com/members/ (this could be a mod-rewrite URL)
then the cookie path will be /members/
. What this means is that if I were to then navigate back to the index, that cookie I set would not be valid for the index and thus not be transferred to the server. In order to make the cookie available to the entire site, no matter which directory you happen to be in, you must specify the 4th argument like so:
setcookie('myCookie', 'TalkPHP.com', time() + 2592000, '/');
The next argument along, number 5), is the domain argument. Again, this will default to the domain you are on. Many problems can arise with this argument, especially with www. and non-www. You see, setting the path to www.talkphp.com
would make the cookie only
available to the www sub-domain. Therefore if I omitted the www the cookie would not register. To get around this you can specify the 5th argument:
setcookie('myCookie', 'TalkPHP.com', time() + 2592000, '/', '.talkphp.com');
Moving swiftly along to the next argument, the secure argument. This simply tells the browser whether or not to transfer the cookie only over a secure connection - HTTPS. If it is set to
then the cookie will only be transferred when the protocol being used is HTTPS and not the plain old HTTP. The default, however, is
which means that the cookie will be sent regardless of the protocol being used at the time. Now we have:
setcookie('myCookie', 'TalkPHP.com', time() + 2592000, '/', '.talkphp.com', false);
setcookie('myCookie', 'TalkPHP.com', time() + 2592000, '/', '.talkphp.com', false, true);
This is truly awesome because it prevents a lot of XSS attacks! All modern day browsers will obey this rule - users still using ancient browsers may still be vulnerable but really that's their own fault for not hitting the oh so prominent update
Note: See our article on Cross-Site Request Forgeries (CSRF) (Cross-Site Scripting (XSS) - sort of).
That's all there is to the
function. Once we have set our cookie, PHP will automatically retrieve it and place it into the $_COOKIE superglobal variable, as well as the $_REQUEST superglobal variable.