How To Use Cookies in an ASP Page (302390)
The information in this article applies to:
- Microsoft Active Server Pages
This article was previously published under Q302390 SUMMARY
Web developers can use cookies in Active Server Pages (ASP) to store and retrieve text-based information on a client browser's computer. Cookies are a great way to persist user information and maintain state with the browser. This article describes how to complete this task.
back to the top
How to Use the Cookies Collection to Save and Retrieve Data
The following steps demonstrate how to use ASP to store and retrieve information to and from a cookie on the client browser:
- From the Windows Start menu, point to Programs, point to Accessories, and then click Notepad.
- Highlight the following code, right-click the code, and then click Copy. In Notepad, click Paste on the Edit menu.
<%@ Language=VBScript %>
<HTML>
<HEAD>
<%
'Creates a cookie with a string value "Hello World!"
Response.Cookies ("MyCookie")="Hello World!"
%>
</HEAD>
<BODY>
<A HREF="CookieGet.asp">Click to get the cookie value</A>
</BODY>
</HTML>
- On the File menu, click Save.
- In the Save As dialog box, click the down arrow in the Save In text box, and click the root of your Web server (which is C:\InetPub\Wwwroot by default). In the Save As Type drop-down list box, click All Files. In the File Name text box, type CookieSet.asp. Finally, click Save.
- In Notepad, create a second file, and paste the following code:
<%@ Language=VBScript %>
<HTML>
<HEAD>
<%
'Displays the value of the cookie "MyCookie" to the browser.
Response.Write Request.Cookies("MyCookie")
%>
</HEAD>
<BODY>
</BODY>
</HTML>
- On the File menu, click Save. Save the file as CookieGet.asp to the same location as the first page.
- Start your Web browser, and type the HTTP location of the page in the Address bar to view the page. If you saved the file in the above-mentioned location, type http://<servername>/CookieSet.asp in the Address bar.
- To view the value of the cookie, type http://<servername>/CookieGet.asp in the Address bar, or click the link that CookieSet.asp provides.
back to the top
Code Explanation
back to the top
More Information
back to the top
Troubleshooting- Two types of cookies exist: in-memory and disk-based cookies, which are stored on the client's disk. The preceding code sample demonstrates the use of in-memory cookies, which are valid until the browser is closed. To save cookies to the client's disk, the following conditions must be met:
back to the top
REFERENCES
For more information about the Cookies collection, see the following Microsoft Web site:
For additional information, click the article numbers below
to view the articles in the Microsoft Knowledge Base:
175167 How To Store State in Active Server Pages Applications
back to the top
Modification Type: | Minor | Last Reviewed: | 6/29/2004 |
---|
Keywords: | kbASPObj kbCodeSnippet kbCookie kbhowto kbHOWTOmaster kbScript KB302390 kbAudDeveloper |
---|
|