↑
Main Page
PHP
?
Name
— The name of the cookie
?
Value
— The value of the cookie
?
Expires
— The date when the cookie expires
?
Path
— The path for the cookie
?
Domain
— The domain for the cookie
?
Secure
— A Boolean indicating whether the cookie is secure
Other properties of
HttpCookie
are used when cookies store multiple values, but since those cookies
won’t work in concert with the JavaScript code in this chapter, they are not listed here.
To read a cookie, you can access it by its name in the
Cookies
collection:
Dim cookie as HttpCookie
Dim cookieValue as String
cookie = Request.Cookies(“name”)
cookieValue = cookie.Value
This example reads a cookie with the name
“name”
and assigns the value to the variable
cookieValue
.
To create a new cookie, create a new instance of
HttpCookie
and pass the name and value to the construc-
tor. Then, you set any other properties for the cookie before saving it with a call to
Response.SetCookie()
:
Dim cookie as HttpCookie = New HttpCookie(“name”, “Nicholas”);
cookie.Expires = #1/1/2006#;
Response.SetCookie(cookie);
Note that the
Expires
property expects a
DateTime
object, not a numeric value as in JSP.
To delete a cookie, just set the
Expires
property to a date in the past:
cookie.Expires = DateTime.Now.addDays(-1);
PHP
PHP’s cookie functions are very straightforward, as is most of the PHP language. To create a cookie,
PHP provides a
setcookie()
function that takes the same arguments as the JavaScript
setCookie()
function described in this chapter. The main difference is that the expiration date is specified as a num-
ber, just as it is in JSP:
bool setcookie ( string name [, string value [, int expire [, string path
[, string domain [, bool secure]]]]])
Calling the function is very easy:
<?php
setcookie(“name”, “Nicholas”);
setcookie(“book”, “Professional JavaScript”);
?>
487
Client-Server Communication
19_579088 ch16.qxd 3/28/05 11:42 AM Page 487
Free JavaScript Editor
Ajax Editor
©
→