ASP Cookies
Cookies are commonly used to identify users.
Try It Yourself - Example
What is a Cookie?
Cookies are commonly used to identify users. A cookie is a small file that the server leaves on the user's computer. Whenever the same computer requests a page through a browser, it will send the cookie too. With ASP, you can create and retrieve the values of cookies.
How to Create a Cookie?
The "Response.Cookies" command is used to create a cookie.
Note: The Response.Cookies command must appear before the <html>
tag.
In the following example, we will create a cookie named "firstname" and set its value to "Alex":
It is also possible to assign attributes to the cookie, such as setting the expiration time:
How to Retrieve a Cookie's Value?
The "Request.Cookies" command is used to retrieve the value of a cookie.
In the following example, we retrieve the value of a cookie named "firstname" and display it on the page:
Output: Firstname=Alex
Cookies with Keys
If a cookie contains a collection of multiple values, we can say that the cookie has keys.
In the following example, we will create a cookie collection named "user". The "user" cookie has keys that contain user information:
Reading All Cookies
Please read the following code:
Assuming your server has sent all the above cookies to a user.
Now, we need to read all the cookies sent to a user. The following example demonstrates how to do this (note that the code checks if the cookie has keys using the HasKeys property):
Output:
firstname=Alex
user:firstname=John
What if the Browser Does Not Support Cookies?
If your application needs to interact with browsers that do not support cookies, you will have to use other methods to pass information between pages in your application. Here are two methods:
1. Adding Parameters to the URL
You can add parameters to the URL:
Then retrieve these values in the "welcome.asp" file, as shown below:
2. Using Forms
You can use forms. When the user clicks the Submit button, the form will pass the user input to "welcome.asp":
Then retrieve these values in the "welcome.asp" file, as shown below: