x

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.

Step 1

Open Notepad or WordPad.

Step 2

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."

Step 3

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.

Tip

  • To check whether any cookie exists, set the value of "cookieToFind" to the name of the cookie you wish to check. You can then check the value of "cookieFound." If that value is "False," the cookie does not exist.

Video of the Day

Brought to you by Techwalla
Brought to you by Techwalla

More Articles