How to Check If a Cookie Exists With ASP

By Kevin Lee

Web cookies help website owners remember their site visitors.These cookies, for example, can store passwords and user IDs so that site visitors do not have to log in manually every time they visit a website. ASP, an older programming language, can create and manage Web cookies. If you are an ASP developer, you can use a convenient "CBool" function to determine if a cookie exists before attempting to process it.

Open Notepad or WordPad.

Paste the following code into a new document:

<%

Response.Cookies("test2") = "testing"

Dim cookieToFind

cookieToFind = "test2"

cookieFound = CBool(Len(Request.Cookies(cookieToFind)) > 0)

response.write("Cookie Found = " & cookieFound)

%>

This creates a simple HTML page that contains a block of ASP code. The "cookieToFind" variable holds the name of the cookie you wish to find. In this instance, that cookie is "test2." The "CBool" VBScript function then checks the result of the "Request.Cookies" request and sets the value of "cookieFound" to "True" if the cookie exists. If the cookie does not exist, it sets variable's value to "False."

Click "File" to open Notepad's "Save As" window. Type a name for the file in the "File Name" text box, and append ".asp" to that name. For instance, if you wish to use the name "ASP1," type "ASP1.asp" into the text box. Click "Save" to save the document.

Upload the file to your Web server. Launch your browser, and navigate to that Web page. When the page loads, the asp code runs and sets a cookie. It then checks to see if it exists and sets the variable named "cookieFound" to "True". The "Response.Write" statement writes "True" to the screen.

×