PHP setting cookies
I learned that when you set cookies, you give them a name, a value, and an expiration. This is an example I got from a book.
setcookie('test', 45, time()(60*60*24));
I understand the purpose of setting a nam开发者_如何学运维e, so we have a way of referring to it. And I understand the purpose of setting the expiry date, but what is the purpose of setting a value? Why would we need to set a value?
The value is the very reason for which you are setting the cookie: so that the next time the browser makes a request, it repeats the value you gave it earlier back to you.
In some occasions, even repeating just the name would be useful (in essence you are getting back one bit of information by the presence or absence of the name). Adding a value lets you keep more than one bit.
So why keep the name if there's going to be a value anyway? Because cookies with different names can have different expiration times, and because it can be convenient for separate components of an application or system to have a cookie dedicated to each one of them. This way, you don't need to account for what component A did to the cookie value when you are setting (overwriting) it from component B. You have a value all to yourself, distinguished by its name.
For completeness, I should mention that there are also other cookie attributes that can be set per-cookie (i.e. per distinct name):
- Domain (cookie is valid only on specific domain and subdomains)
- Path (cookie is valid only on specific request path and below)
- Secure/HttpOnly (however, these cookies can have no value)
Cookies are key = value pairs. Just the presence of a cookie could be useful (even if nothing), but it's ultimately meant to store a value retrievable by key (name).
And technically you don't need the value or expiry: http://php.net/manual/en/function.setcookie.php
The value of the cookie. This value is stored on the clients computer; do not store sensitive information. Assuming the name is 'cookiename', this value is retrieved through $_COOKIE['cookiename']
Also Check: PHP setcookie Manual; PHP setcookie Function
精彩评论