Session Replacement in ASP - Session Check
(Page 3 of 5 )
For the sake of simplicity, the ASP application consists of only two pages: a home page for which a login is required, and the login page where the user can enter a username and password which will be validated. Add the following ASP code snippet to the top of the home page:
<%
Dim oCnn, oRs
If Len(Request.QueryString(“id”)) = 0 Then
Response.Redirect “login.asp”
End If
Set oCnn = Server.CreateObject(“ADODB.Connection”)
OCnn.Open “dsn=myDSN;uid=MyUid;pwd=myPwd;”
Set oRs = oCnn.Execute(“EXECUTE usp_CheckSessionID @sessionID = ‘“ & _
Request.QueryString(“id”) & “’”)
If Not oRs.Fields(0).Value = 0 Then
ORs.Close
OCnn.Close
Set oCnn = Nothing
Response.Redirect “login.asp”
End If %>
Since this solution uses querystrings, we first need to test for the existance of the right querystring:
If Len(Request.QueryString(“id”)) = 0 Then
Response.Redirect “login.asp”
End If
I found the easiest way to check whether a querystring exists, is to test for the length of the querystring. If the length is 0 than the querystring does not exist; we than simply redirect to the login page and are done.
Set oCnn = Server.CreateObject(“ADODB.Connection”)
OCnn.Open “dsn=myDSN;uid=MyUid;pwd=myPwd;”
Set oRs = oCnn.Execute(“EXECUTE usp_CheckSessionID @sessionID = ‘“ & _
Request.QueryString(“id”) & “’”)
I will not explain the use of ADO any further in this article. There are many who have done a masterful job describing the inner workings of ADO connections and recordset objects, and they have done it much better then I ever can. Take a look at DevArticles SQL Server section.
If the querystring value is found, we open a connection to the database and call the stored procedure usp_CheckSessionID. Note that the id needs to be single quoted, as this is what SQL server requires from a parameter of type uniqueidentifier.
If Not oRs.Fields(0).Value = 0 Then
ORs.Close
OCnn.Close
Set oCnn = Nothing
Response.Redirect “login.asp”
End If
The stored procedure returns a 1 row by 1 column recordset and therefore the value is captured in oRS.Fields(0).Value. You may find the
If Not ... = 0 Then
a little cryptic, but I am one of these people who test for true or not true. Anyway, if the value is not 0, then we redirect to the login page which is described in the next section.
Next: The Login Page >>
More ASP Articles
More By Rogier Doekes