View Full Version : Simple cookie checking with ASP

01-03-2007, 03:28 PM
I have read a couple of posts on how to check whether cookies are enabled with ASP. The solutions I have seen suggest the following kind of code:

Session("test") = "something"
If Session("test") = "something" Then
Response.Write "Session enabled"
Response.Write "Session not enabled"
End If

Response.Cookies("test") = "something"
If Request.Cookies("test") = "something" Then
Response.Write "Cookies enabled"
Response.Write "Cookies not enabled"
End If

The problem with this code is that it will always return that cookies are enabled. This is due to the fact that cookies are sent as headers and their status can only be validated on a client or by reloading the page.

I use the frame apporach to test cookies - for demostration I use visible IFRAME, but it can of course also be used with hidden frames to hide the checking from end-users

'SET sesison and cookie value
sSessionValue = "Session cookies are enabled"
sCookieValue = "Persistent cookies are enabled"

Session("session-test") = sSessionValue
Response.Cookies("cookie-test")("test") = sCookieValue
Response.Cookies("cookie-test").Expires = Date + 1

'Check if cookies are enabled
Response.Write "<h1>Cookie checking on a single page</h1>"
Response.Write "<div>" & Session("session-test") & "</div>"
Response.Write "<div>" & Request.Cookies("cookie-test")("test") & "</div>"
Response.Write "<div style=""height:20px;""><!-- --></div>"
<iframe src="cookie_test2.asp?sc=<% = sSessionValue %>&pc=<% = sCookieValue %>"
width="500" height="500" frameborder="1"></iframe>

Response.Write "<h1>Cookie checking on two pages</h1>"

If Session("session-test") = Request.QueryString("sc") Then
Response.Write Session("session-test")
Response.Write "Session cookies are disabled!"
End If

Response.Write "<br />"

If Request.Cookies("cookie-test")("test") = Request.QueryString("pc") Then
Response.Write Request.Cookies("cookie-test")("test")
Response.Write "Persistent cookies are disabled!"
End If

I hope this will be helpful to some of you. :thumbsup: