ASP Cookies
Collection
The Cookies collection is used to set or retrieve the value of a cookie. If the cookie does not exist, it creates it and assigns it the specified value.
Note: The Response.Cookies command must be placed before the <html>
tag.
Syntax
Parameter | Description |
---|---|
name | Required. The name of the cookie. |
value | Required (for the Response.Cookies command). The value of the cookie. |
attribute | Optional. Specifies information about the cookie. Can be one of the following parameters: Domain - Write-only. The cookie is sent only to requests made to this domain. <br> Expires - Write-only. The expiration date of the cookie. If no date is specified, the cookie expires when the session ends. <br> HasKeys - Read-only. Specifies whether the cookie has keys (this is the only attribute that can be used with the Request.Cookies command). <br> Path - Write-only. If set, the cookie is sent only to requests made to this path. If not set, the application path is used. <br> Secure - Write-only. Indicates whether the cookie is secure. |
key | Optional. Specifies the key where the value is assigned. |
Examples
The "Response.Cookies" command is used to create a cookie or set its value:
In the above code, we created a cookie named "firstname" and assigned it the value "Alex".
You can also set attributes for the cookie, such as its expiration time:
Now, the cookie named "firstname" has the value "Alex" and it will expire on the user's computer on May 10, 2002.
The "Request.Cookies" command is used to retrieve the value of a cookie.
In the following example, we retrieve the value of the cookie "firstname" and display it on the page:
A cookie can contain a collection of multiple values. We call this a cookie with keys.
In the following example, we create a cookie collection named "user". The "user" cookie contains keys with user information:
The following code reads all cookies sent by the server to the user. Note that we use the HasKeys property to check if the cookie has keys:
Output:
user:firstname=John