![]() |
Taking a Bite out of the Set Cookie Function
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.
PHP Code:
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:PHP Code:
PHP Code:
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:PHP Code:
PHP Code:
Code:
<script type="text/javascript">Note: See our article on Cross-Site Request Forgeries (CSRF) (Cross-Site Scripting (XSS) - sort of). 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. |
Hey, great article.
You personally, would you recommended setting the 7th argument to true at all times? From your description, I think I would do, unless it has any limitations. |
Really great article! Love it :D
GOod job |
| All times are GMT. The time now is 03:28 PM. |
Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.1.0