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.
The setcookie() 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 setcookie() 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:
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:
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 true then the cookie will only be transferred when the protocol being used is HTTPS and not the plain old HTTP. The default, however, is false which means that the cookie will be sent regardless of the protocol being used at the time. Now we have:
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 button.
That's all there is to the setcookie() 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.
The man who comes back through the Door in the Wall will never be quite the same as the man who went out.
Last edited by Wildhoney : 09-29-2007 at 11:31 AM.