Cookies in PHP - Cookie Attributes
(Page 3 of 4 )
I mentioned earlier that cookies can also be assigned several attributes: an expiration date, a valid domain, a valid domain path and an optional security flag.
The expiration time is used by the browser to determine when the cookie should be deleted. It is expressed as a Unix timestamp plus the number of seconds before the cookie expires.
The valid domain is a partial or complete domain name to which the cookie will be sent. For example, if the value for the valid domain attribute is "www.example.net", the client will send the cookie information every time the user visits the www.example.net subdomain. For the cookie to be accessible within all subdomains of example.net (such as www.example.net, mail.exaple.net, news.example.net, users.example.net, etc.), a leading dot should be used as in ".example.net".
The path attribute is used to identify sites within various paths in the same domain. For example, cookies with a path attribute of "/" will be both accessible to users.example.net/~tom and users.example.net/~sally. However, a cookie with a path attribute of "/~tom" will only be made available to users.example.net/~tom, not users.example.net/~sally.
The security flag attribute restricts a browser from sending cookie information over unsecured connections. The default value is 0 and allows the cookie to be sent over any type of HTTP connection. It may be set to 1 which will only permit the cookie to be sent over a secure HTTP (HTTPS) connection.
The setcookie function accepts not only a key/value pair, but also any of the attributes mentioned above. The syntax for setcookie is setcookie(name, value, [[expiration], [path], [domain], [security]]).
setcookie("favoriteColor", "blue", time() + 60 * 60 * 24 * 30, "/~tom", "users.example.com", 1); will generate a cookie storing "blue" as $_COOKIE["favoriteColor"]. The cookie will expire after 30 days, and should be made available only if a secure connection has been established to https://users.example.com/~tom.
Next: Words Of Caution >>
More Programming Basics Articles
More By bluephoenix