Active Server Pages: Application Objectcontext Request Response Server Session
Active Server Pages: Application Objectcontext Request Response Server Session
Note:
• The web server must be setup to allow script or execute
permissions on the virtual directory where the ASP code will
reside.
• The file containing the ASP code must have .asp extension
otherwise the web server does not process the server-side script
code.
The server-side script code uses <% and %> tags to identify the code that
will get executed on the server. The scripting language in this case is the
default language set up on the server.
136
Example:
<!-- Serversc1.asp -->
<% @ LANGUAGE=VBScript%>
<HTML>
<HEAD>
<TITLE> Server side scripting - Reporting the Date and Time on the Server </TITLE>
</HEAD>
<BODY>
<H2> <CENTER> Server Side Scripting </CENTER> </H2>
<H3> <CENTER> Date and Time on the server =
<%
dim t1
t1 = now
Response.write t1
%>
</CENTER></H3>
<HR>
</BODY>
</HTML>
137
Note that if you save the Serversc1.asp file in the previous example as
Serversc1.htm, and retrieve it from your browser, the web server does not
execute the server-side script code and passes it as is to the Client browser.
Change the file name back to Serversc1.asp and examine it in the browser.
Then try to view the source from the browser, you will note that the server-
side script code is not visible to the browser, it only gets the HTML
statements.
Result of View -> Source from the browser when the Serversc1.asp file is
being viewed.
<!-- Serversc1.asp -->
<HTML>
<HEAD>
<TITLE> Server side scripting - Reporting the Date and Time on the Server </TITLE>
</HEAD>
<BODY>
<H2> <CENTER> Server Side Scripting </CENTER> </H2>
<H3> <CENTER> Date and Time on the server =
4/8/00 6:49:57 AM
</CENTER></H3>
138
<HR>
</BODY>
</HTML>
You can embed HTML tags inside the ASP Response.write method to format
the output e.g., if you wanted the date and time on the server to appear on
the next line, you would change the Response.write statement as:
Example:
<!-- Serversc3.asp -->
<% @ LANGUAGE=VBScript%>
<HTML>
<HEAD>
<TITLE> Server side scripting - Reporting the Date and Time on the Server </TITLE>
</HEAD>
<BODY>
<H2> <CENTER> Server Side Scripting </CENTER> </H2>
<H3> <CENTER> Date and Time on the server = <%= now %>
</CENTER></H3>
<HR>
</BODY>
</HTML>
Exercise: Try substituting <% = now %> by <% = t1 = now %> and see
how the browser displays it.
Exercise: Try modifying the code as shown below:
<!-- Serversc4.asp -->
<% @ LANGUAGE=VBScript%>
<HTML>
<HEAD>
<TITLE> Server side scripting - Reporting the Date and Time on the Server </TITLE>
</HEAD>
<BODY>
<H2> <CENTER> Server Side Scripting </CENTER> </H2>
<%
dim t1
t1 = now
%>
<H3> <CENTER> Date and Time on the server = <%= t1 %>
139
</CENTER></H3>
<HR>
</BODY>
</HTML>
Exercise: Try retyping the url in the browser (or just a part of it) i.e.,
http://localhost/MyWeb/Serversc4.asp and see if the time changes.
Response.expires
By placing <% Response.expires = 0 %>, you can indicate to the browser
not to cache the page. This way the time will be obtained from the server
each time the user comes to this page.
<% @ LANGUAGE=VBScript%>
<% Response.expires=0 %>
<!-- Serversc5.asp -->
<HTML>
<HEAD>
<TITLE> Server side scripting - Reporting the Date and Time on the Server </TITLE>
</HEAD>
<BODY>
<H2> <CENTER> Server Side Scripting </CENTER> </H2>
<%
dim t1
t1 = now
%>
<H3> <CENTER> Date and Time on the server = <%= t1 %>
</CENTER></H3>
<HR>
</BODY>
</HTML>
If you try viewing the above page in your browser, you will get an error
message:
The reason for the error is that the Response.expires= should be specified
before any HTML content is sent to the page i.e., this needs to be in the
header section in the response. So the HTML comment line which appears
two lines before <% Response.expires=0 %> is the source of the problem.
Modify the first few lines of the page as shown below:
<% @ LANGUAGE=VBScript%>
140
Now try viewing this page and retyping part of the url to see if the time is
correctly updated.
You can also specify a relative or absolute time for the page to expire in the
cache of the browser, e.g.,
Response.ExpiresAbsolute=#6/1/2000 06:30:00#
Or
Try viewing the above file in your browser and you will see that it does not
show any date and time. Now modify the above file to create a function that
will return date and time as shown below:
<% @ LANGUAGE=VBScript%>
141
Security Concern: Try viewing the include file directly in the browser i.e.,
type the url as:
143
http://localhost/MyWeb/include/greet.inc.txt
Even though you will not be able to view anything in the page, if you try to
view the source (View->source from the browser menu), you will be able to
see the ASP function code. In some practical situations, we may not want
the client to be able to take a look at our ASP code, hence any extension
other than an .asp for the INCLUDE files does not protect your ASP code
from the client.
Now the client browser cannot see the code in the greet.asp file even if this
file is viewed in the browser directly.
Response.expires=0 revisited:
Response.expires=0 causes the browser to not to cache the web page. This
may be important for periodically changing data in the page such as server
time, or stock quotes etc.. However, from performance point of view, setting
expires=0 also causes a refetch of the page from the server. If the page
involves a little dynamic data but quite a bit of images that do not change
over time, then the page loading could become slow.
It is possible to break the page into a few different asp files some
having a setting of Response.expires=0 and some with a greater expiration
time. The asp files are not included by an #INCLUDE statement but rather
by a client-side JavaScript SRC statement.
Example:
<% @ LANGUAGE=VBScript%>
<% Response.expires=0 %>
144
<HTML>
<HEAD>
<TITLE> Server side scripting - Response.redirect method </TITLE>
</HEAD>
<BODY>
<H2> <CENTER> Server Side Scripting </CENTER> </H2>
<H3> <CENTER> Date and Time on the server = <% Response.write(Now) %>
</CENTER></H3>
<HR>
</BODY>
</HTML>
Buffering Output:
Both Response.expires=0 and Response.redirect require that no HTML
content is written before executing them. However, in some dynamic
situations, we may want to change the expiration time or redirecting to a
different site. This can be accomplished by buffering the output by setting
Response.buffer=TRUE
If page buffering is on, then expiration can be changed any time later, even if
some HTML content has been written to the buffer but not sent to the
browser.
If the page is being buffered, then it can be sent from the server to the
browser either by executing Response.flush or Response.end method.
Example:
<% @ LANGUAGE=VBScript%>
<%
Response.buffer=True 'This is required if redirection is needed
'after some content has been written
Response.expires=1 '1 minute expiration
%>
<!-- Serversc13.asp -->
<HTML>
<HEAD>
<TITLE> Server sside scripting - Response.redirect method </TITLE>
</HEAD>
<BODY>
<H2> <CENTER> Server Side Scripting - Response.redirect </CENTER> </H2>
<%
Response.write "We are redirecting you to a different page"
If Hour(now) < 12 Then
Response.redirect "serversc5.asp"
else
147
Response.redirect "http://www.amazon.com"
end if
%>
<H3> <CENTER> Date and Time on the server = <% Response.write(Now) %>
</CENTER></H3>
<HR>
</BODY>
</HTML>
Response.ContentType
This identifies to the browser how the content should be displayed.
For example, if Response.ContentType=”text/plain” then the browser does
not interpret HTML tags. However if the
Response.ContentType=”text/html” then the HTML tags are taken into
account. If Response.ContentType=”application/msword” then the internet
explorer displays the page by opening MS WORD in the browser.
148
Example:
<% @LANGUAGE=VBSCRIPT %>
<% 'Serversc15.asp
Response.ContentType="text/plain"
'Change the content type to text/html and view the page
'to see how html tags are interpreted correctly
Response.expires=0
%>
ASP is easy to learn and you can create very useful Web
applications relatively quickly, with it
Request Object
One important collection of the request object is ServerVariables
which provides information about the environment variables such as IP
address of the client, length of the posted content, browser information etc..
strSelf = Request.ServerVariables(“SCRIPT_NAME”)
returns virtual path of the asp page itself
nLength = Request.ServerVariables(“CONTENT_LENGTH”)
returns length of the posted content (POST method)
149
You can determine all HTTP headers sent from the browser by executing the
following code:
Example:
<% @ LANGUAGE=VBSCRIPT %>
<% 'Serversc16.asp %>
<HTML>
<HEAD>
<TITLE>
Test of HTTP headers determined from the Request Object
</TITLE>
<HEAD>
<BODY>
<H2> Some HTTP headers as determined from the Request object </H2>
<%
strSelf = Request.ServerVariables("SCRIPT_NAME")
Response.write("My page URL is: " & strSelf)
strBinfo = Request. ServerVariables("HTTP_USER_AGENT")
Response.write("<BR>Browser name and platform is: " & strBinfo)
When GET method is used to submit a FORM to the server, the server
script can use the Request.querystring collection to determine the values of
different fields.
In the GET method, querystring is appended to the URL when the form is
submitted. Each element in the form is identified by its name=value. The
different elements are separated by & e.g., an ID and password form when
submitted using the GET method will have the following querystring:
http://mango/HTMLEx/Serversc17a.asp?USERID=965&PASSWORD=45&cmdLogin=Login
Example:
<% @LANGUAGE=VBSCRIPT %>
<% 'Serversc17.asp %>
<HTML>
<HEAD>
<TITLE> GET method to Submit a FORM</TITLE>
</HEAD>
<BODY>
<H2> Web Site Logon </H2>
<H3> Please Specify User ID and Password</H3>
<HR>
<FORM method=GET ACTION="Serversc17a.asp">
User ID: <INPUT NAME="USERID" SIZE="5" MAXLENGTH="5" VALUE="673">
Password: <INPUT TYPE="password" NAME="PASSWORD" SIZE="8" MAXLENGTH="8"
VALUE="">
<INPUT TYPE=SUBMIT VALUE="Login" NAME=cmdLogin>
<HR>
</FORM>
</BODY>
</HTML>
The target of a GET or POST method can be the page itself, e.g. the above
program can be modified as:
<% @LANGUAGE=VBSCRIPT %>
<% 'Serversc18.asp %>
<HTML>
<HEAD>
<TITLE> GET method to Submit a FORM</TITLE>
</HEAD>
<BODY>
<H2> Web Site Logon </H2>
<HR>
<% If Request.ServerVariables("QUERY_STRING") = "" Then %>
<H3> Please Specify User ID and Password</H3>
<FORM method=GET ACTION="Serversc18.asp">
User ID: <INPUT NAME="USERID" SIZE="5" MAXLENGTH="5" VALUE="673">
Password: <INPUT TYPE="password" NAME="PASSWORD" SIZE="8" MAXLENGTH="8"
VALUE="">
<INPUT TYPE=SUBMIT VALUE="Login" NAME=cmdLogin>
<HR>
</FORM>
<% Else
Response.write("UserID submitted = " & Request.querystring("USERID"))
Response.write("<BR>Password submitted = " & Request.querystring("PASSWORD"))
End If
%>
</BODY>
</HTML>
It is a good practice to not to hard code the asp page name in the FORM’s
ACTION attribute. Instead, you should use the
Rquest.ServerVariables(“SCRIPT_NAME”).
Change the following line in the above program:
<FORM method=GET ACTION="Serversc18.asp"> to
<FORM method=GET ACTION= “<%=Request.ServerVariables(“SCRIPT_NAME”)%>”>
POST method:
GET method allows only 2KB of data to be appended to the querystring. If
data submitted from a form is larger, then use the POST method.
In the POST method, use Request.ServerVariables("CONTENT_LENGTH") to
determine if the form has been filled or not. Also use
Request.Form(“element name”) to obtain the value of an HTML form
element.
Example:
<% @LANGUAGE=VBSCRIPT %>
152
Data validation can be done on the client side before submitting the form.
<% @LANGUAGE=VBSCRIPT %>
<% 'Serversc20.asp %>
<HTML>
<HEAD>
<TITLE> POST method to Submit a FORM</TITLE>
</HEAD>
<SCRIPT LANGUAGE=VBSCRIPT>
<!--
Sub cmdSubmit_OnClick()
If (Trim(frmFB.txtName.value) = "") OR (Trim(frmFB.txtID.Value) = "") Then
MsgBox("You must enter a Name and ID before submitting form")
window.event.returnvalue=False
End If
End Sub
-->
</SCRIPT>
<BODY>
<H2> Web Site Feedback </H2>
<HR>
<% If Request.ServerVariables("CONTENT_LENGTH") = 0 Then %>
<H3> Please Enter Name, UserID and some Comments </H3>
<FORM NAME=frmFB method=POST ACTION= <%=Request.ServerVariables("SCRIPT_NAME")%>">
<PRE>
153
The html code for the two linked pages is shown below:
<!-- news.htm -->
<HTML>
<HEAD>
<TITLE> XYZ Corporation News </TITLE>
</HEAD>
<BODY>
<H2> XYZ stock hits all time Low </H2>
The recent stock market crash has caused the XYZ stock to below
its IPO value. The president of the company is however, very optimistic
that the company fundamentals are strong and would like to encourage
the employees to have faith in his leadership and volunteer for a 10%
cut in salary (money is not everything, he says).
</BODY>
</HTML>
<HTML>
<HEAD>
<TITLE> Salaries of important personnel </TITLE>
</HEAD>
<BODY>
Salaries for Year 2000 - XYZ Corporation
<HR>
<TABLE Border=1>
<TR> <TH> Employee_Name <TH> Salaray </TR>
<TR> <TD> John Jacobs <TD> $38,500 </TR>
<TR> <TD> Sally Simpson <TD> $48,700 </TR>
<TR> <TD> Mark Mathews <TD> $43,200 </TR>
<TR> <TD> Trish Townsend <TD> $68,800 </TR>
</TABLE>
</BODY>
</HTML>
Your goal is add security to the salaries page so that only allowed company
officials are allowed to view the salaries of employees.
Solution (First Attempt, put a password protection to entire site):
<% @LANGUAGE=VBSCRIPT %>
<%' indexa.asp %>
<%
Response.Buffer = True
Response.expires = 0
%>
<HTML>
<HEAD>
<TITLE> XYZ Corporation Logon </TITLE>
</HEAD>
<BODY>
<H2> XYZ Corporation - Program-based Security </H2>
<HR>
<% If Request.ServerVariables("CONTENT_LENGTH") = 0 Then %>
<H3> Please Specify User Name and Password </H3>
<FORM method=POST ACTION="<%=Request.ServerVariables("SCRIPT_NAME")%>">
<PRE>
User Name: <INPUT NAME="txtUserName" SIZE="15" MAXLENGTH="15" VALUE="">
Password: <INPUT TYPE="password" NAME="txtPassword" SIZE="8" MAXLENGTH="8"
VALUE="">
</BODY>
</HTML>
<% 'AuthenticateUser.asp
dim strUsername
dim strPassword
dim strURL 'URL of the secured document requested by the user
strUsername = UCase(Request.Form("txtUsername"))
strPassword = UCase(Request.Form("txtPassword"))
Function VerifyLogin
dim objCLC
dim count
dim strRUsername 'registered username
dim strRPassword 'registered user Password
dim strFile
strFile = "RegisteredUsers.txt"
Sub ReportLoginStatus(matchfound)
If matchfound = true Then 'User has a proper password entry in registered users
Response.write "Welcome " & strUsername & "<BR>"
else
Response.write "Incorrect login <BR>"
Response.write "Click the BACK button in the browser to try login again"
Response.End
end if
end Sub
%>
RegisteredUsers.txt
Rawlins rigel4
156
Mahmood mango55
Andrews awk77
Samson sharky
Index.htm
<!-- index.htm -->
<HTML>
<HEAD>
<TITLE> Main Page - Welcome to XYZ Corporation </TITLE>
</HEAD>
<BODY>
<H2> Main Page - Welcome to XYZ Corporation </H1>
<H2> Important Links </H2>
<BR>
<A HREF="salaries.asp"> Salaries of Employees (password protected) </A>
<BR> <BR>
<A HREF="news.htm"> Current News about XYZ Corporation </A>
<BR> <BR>
<A HREF="empreviews.asp"> Employee Reviews for 1999 at XYZ Corporation </A>
</BODY>
</HTML>
157
FormLogin.asp
<% @LANGUAGE=VBSCRIPT %>
<% 'FormLogin.asp
Response.expires = 0 'do not cache the login page
Session.Timeout=1 '1 minute instead of 20 minute default
If Session.Contents("RequestedURL")="" Then
Session.Contents("RequestedURL")="index.htm"
End If
%>
<HTML>
<HEAD>
<TITLE> Secure Page Logon </TITLE>
</HEAD>
<BODY>
<H2> Program-based Security </H2>
<HR>
<H3> Please Specify User Name and Password </H3>
<FORM method=POST ACTION="AuthenticateUsera.asp">
<PRE>
User Name: <INPUT NAME="txtUserName" SIZE="15" MAXLENGTH="15" VALUE="">
Password: <INPUT TYPE="password" NAME="txtPassword" SIZE="8" MAXLENGTH="8"
VALUE="">
RegisteredUsers.txt
Rawlins rigel4
Mahmood mango55
Andrews awk77
Samson sharky
AuthenticateUsera.asp
<% 'AuthenticateUsera.asp
'Verify if a user submitted a correct password by reading username
'and password from RegisteredUsers.txt file
dim strUsername
dim strPassword
dim strURL 'URL of the secured document requested by the user
strUsername = UCase(Request.Form("txtUsername"))
strPassword = UCase(Request.Form("txtPassword"))
strURL = Session.Contents("RequestedURL")
If Trim(strURL) = "" Then
strURL="index.htm"
End If
158
Function VerifyLogin
dim objCLC
dim count
dim strRUsername 'registered username
dim strRPassword 'registered user Password
dim strFile
strFile = "RegisteredUsers.txt"
'open content link file
Set objCLC = Server.CreateObject("MSWC.NextLink")
count = objCLC.GetListCount(strFile)
dim i, Found
Found = false
Session.Contents("Username") = "" 'clear old value
For i = 1 to count 'number of registered users
strRUsername = UCase(objCLC.GetNthURL(strFile,i))
strRPassword = UCase(objCLC.GetNthDescription(strFile,i))
If strUsername = strRUsername and strPassword=strRPassword Then
Found = true
Session.Contents("Username") = strUsername
exit FOR
End If
Next
VerifyLogin = Found
End Function
Sub ReportLoginStatus(matchfound)
If matchfound = true Then 'User has a proper password entry in registered users
Response.write "Welcome " & strUsername & "<BR>"
Response.write "Click here to continue" & _
"<A HREF=" & chr(34)&strURL&chr(34) & ">" & strURL & "</A>"
else
Response.write "Incorrect login <BR>"
Response.write "Click the BACK button in the browser to try login again"
Response.End
end if
end Sub
%>
ProtectbyPass.asp:
<% 'ProtectbyPass.asp
Salaries.asp
<% Response.buffer = True %>
<!-- #include FILE="ProtectbyPass.asp" -->
<%' Salaries.asp %>
<HTML>
<HEAD>
<TITLE> Salaries of important personnel </TITLE>
</HEAD>
<BODY>
Salaries for Year 2000 - XYZ Corporation
<HR>
<TABLE Border=1>
<TR> <TH> Employee_Name <TH> Salaray </TR>
<TR> <TD> John Jacobs <TD> $38,500 </TR>
<TR> <TD> Sally Simpson <TD> $48,700 </TR>
<TR> <TD> Mark Mathews <TD> $43,200 </TR>
<TR> <TD> Trish Townsend <TD> $68,800 </TR>
</TABLE>
<% Response.write "Session variable Username = " & Session.Contents("Username")
Response.write "<BR>Session ID = " & Session.SessionID
%>
</BODY>
</HTML>
News.htm
<!-- news.htm -->
<HTML>
<HEAD>
<TITLE> XYZ Corporation News </TITLE>
</HEAD>
<BODY>
<H2> XYZ stock hits all time Low </H2>
The recent stock market crash has caused the XYZ stock to below
its IPO value. The president of the company is however, very optimistic
that the company fundamentals are strong and would like to encourage
the employees to have faith in his leadership and volunteer for a 10%
cut in salary (money is not everything, he says).
</BODY>
</HTML>
EmpReviews.asp
<!-- empreviews.asp -->
<HTML>
<HEAD>
<TITLE> XYZ Employee Reviews </TITLE>
</HEAD>
<BODY>
<H2> XYZ Employee Reviews 1999 - Confidential </H2>
<TABLE BORDER=3>
<TR> <TH> Employee Name <TH> Performance (Max=10) <TH> Comments </TR>
<TR> <TD> John Jacobs <TD> 7.5 <TD> Needs to take more initiative </TR>
<TR> <TD> Sally Simpson <TD> 6.0 <TD> Always running behind </TR>
160
<TR> <TD> Mark Mathews <TD> 5.5 <TD> Slow worker </TR>
<TR> <TD> Trish Townsend <TD> 4.5 <TD> Overpaid employee </TR>
</TABLE>
Comments: May be a pay cut will motivate these employees
</BODY>
</HTML>
Salaries.asp (modified):
<% Response.buffer = True %>
<!-- #include FILE="ProtectbyPass.asp" -->
<%' Salaries.asp %>
<HTML>
<HEAD>
<TITLE> Salaries of important personnel </TITLE>
</HEAD>
<BODY>
Salaries for Year 2000 - XYZ Corporation
<HR>
<TABLE Border=1>
<TR> <TH> Employee_Name <TH> Salaray </TR>
<TR> <TD> John Jacobs <TD> $38,500 </TR>
<TR> <TD> Sally Simpson <TD> $48,700 </TR>
<TR> <TD> Mark Mathews <TD> $43,200 </TR>
<TR> <TD> Trish Townsend <TD> $68,800 </TR>
</TABLE>
<% Response.write "Session variable Username = " & Session.Contents("Username")
Response.write "<BR>Session ID = " & Session.SessionID
%>
<FORM method=POST Action="Logout.asp">
<INPUT TYPE=Submit VALUE="Logout" Name=cmdLogout>
</FORM>
</BODY>
</HTML>
<BODY>
<H3> Test of All Page Hit Count </H3>
<HR>
All Page Hits = <%= Application(“AllPageHitsCount”) %>
</BODY>
</HTML>
Sub Session_OnStart
'The user name and the page variable are empty at first
Session.Contents("Username")=""
Session.Contents("ReuestedURL")=""
End Sub
Sub Application_OnStart
Application.Lock
Application("AllPageHitsCount") = 0
Application.Unlock
End Sub
</SCRIPT>
Sub Session_OnStart
'The user name and the page variable are empty at first
Session.Contents("Username")=""
Session.Contents("ReuestedURL")=""
Session("AllSessionHits") = 0
End Sub
163
Sub Application_OnStart
Application.Lock
Application("AllPageHitsCount") = 0
Application.Unlock
End Sub
</SCRIPT>
Sub Session_OnStart
'The user name and the page variable are empty at first
Session.Contents("Username")=""
Session.Contents("ReuestedURL")=""
Session("AllSessionHits") = 0
Application.Lock
Application("CurrentUserCount")= Application("CurrentUserCount")+1
Application("AllUserCount")=Application("AllUserCount") + 1
Application.Unlock
End Sub
Sub Application_OnStart
Application.Lock
Application("AllPageHitsCount") = 0
Application("CurrentUserCount")=0
Application("AllUserCount")=0
Application.Unlock
End Sub
Sub Session_OnEnd
Application.Lock
164
Application("CurrentUserCount")= Application("CurrentUserCount")-1
Application.Unlock
End Sub
</SCRIPT>
165
Permanent Cookies
Session cookies as demonstrated in the previous few pages are stored on the
web server for a particular session as identified by the session ID which is
stored in the browser and submitted with each page request to the server.
The default lifetime of session variables or session cookies is 20 minutes.
Sometimes we need to store the information for a longer period of time. This
can be achieved by using permanent cookies that are stored on the client
computer’s hard disk and identified by the web server. The values contained
in the cookie file is presented to the web server each time user visits the
server web site.
Example:
Response.Cookies(“Username”) = “mahmood”
Response.Cookies(“Username”).Expires = DateAdd(“m”,2,Now)
Will store a cookie called Username for two months on the client
machine.
Exercise: Modify the FormLogin.asp such that the username and password
are read from a cookie called “User” and their value entered in the username
and password text boxes. Also modify the AuthenticateUsera.asp file such
that once the username and password are verified, a cookie dictionary called
“User” is stored on the client machine having fields of username and
password.
166
Solution:
<% @LANGUAGE=VBSCRIPT %>
<% 'FormLogina.asp
Response.expires = 0 'do not cache the login page
Response.buffer=True 'otherwise causes starnge behavior when loading the
'page first time
Session.Timeout=1 '1 minute instead of 20 minute default
If Session.Contents("RequestedURL")="" Then
Session.Contents("RequestedURL")="index.htm"
End If
%>
<HTML>
<HEAD>
<TITLE> Secure Page Logon </TITLE>
</HEAD>
<BODY>
<H2> Program-based Security </H2>
<HR>
<H3> Please Specify User Name and Password </H3>
<FORM method=POST ACTION="AuthenticateUsera.asp">
<PRE>
<% 'following script added for permanent cookies related to username, Password
dim UNM, PW
UNM = Request.Cookies("User")("UName")
PW = Request.Cookies("User")("UPass")
%>
User Name: <% Response.write "<INPUT NAME=txtUsername SIZE=15 "
Response.write "MAXLENGTH=15 VALUE=" & chr(34)&UNM&chr(34) & ">" %>
Password: <INPUT TYPE=password NAME=txtPassword SIZE=8
MAXLENGTH=8 VALUE="<%=PW%>">
<INPUT TYPE=SUBMIT VALUE="Submit Name AND Password" NAME=cmdLogin>
<HR>
</PRE>
</FORM>
</BODY>
</HTML>
Modification to AuthenticateUsera.asp:
…..
Sub ReportLoginStatus(matchfound)
If matchfound = true Then 'User has a proper password entry in registered users
' following lines added for permanent cookies related to
' user name and password ----------------------------
Response.Cookies("User")("UName") = strUserName
Response.Cookies("User")("UPass") = strPassword
Response.Cookies("User").Expires=DateAdd("m",1,now())
'----------------------------------------------------
Response.write "Welcome " & strUsername & "<BR>"
Response.write "Click here to continue" & _
"<A HREF=" & chr(34)&strURL&chr(34) & ">" & strURL & "</A>"
else
167
For session cookies to be stored on the Web server, the browser requesting
the page must have session cookies enabled on it (otherwise the browser
cannot store SessionID in it).
Two checks are needed in this case, first one to see if the page is being
called first time, if so then we create a session variable and an artificial
query string, and then reinvoke the same page. In the second invocation, the
session variable’s value is checked to see if we were able to store it or not.
Note that the artificial query string is needed to determine if page was called
first time or second time.
Example:
<% @LANGUAGE = VBScript %>
<% Option Explicit 'Serversc25.asp %>
<%
Dim QryStr
Response.Expires = 0 ' important!
If Session("CheckCookie") <> "Chocolate" then
QryStr = Request.ServerVariables("QUERY_STRING")
If Request.QueryString("call") = "second" Then
QryStr = Mid(QryStr,Len("call=second&")+1)
If QryStr <> "" Then
QryStr = "?" & QryStr
End If
%>
<HTML>
<TITLE> Checking if Cookies are Enabled </TITLE>
<BODY>
<body bgcolor=#ff0000>
Your browser does not accept cookies, however, this site
needs Cookies enabled.
<A HREF="<%=Request.ServerVariables("SCRIPT_NAME") & QryStr %>"> Click here</A>
after you have enabled cookies.
</BODY>
</HTML>
<%
Response.End
168
Else 'user has called the page first time so set a session cookie
'and add something to Query String so that second call can check
'if cookie exists as ot was set
Session("CheckCookie") = "Chocolate"
If QryStr <> "" Then
QryStr = "?call=second&" & QryStr
Else
QryStr = "?call=second"
End If
Response.Redirect Request.ServerVariables("SCRIPT_NAME") & QryStr
End If
End If
%>
<html>
<body bgcolor=#00ff00f>
Your browser accepts cookies!
</body>
</html>
Example:
<% @LANGUAGE = VBScript %>
<% 'Serversc27.asp
Option Explicit
%>
<HTML>
<HEAD>
<TITLE> Using MSWC.BrowserType ActiveX Component for Testing Cookie Capability </TITLE>
170
</HEAD>
<BODY>
<%
Dim Bobj
Set Bobj = Server.CreateObject("MSWC.BrowserType") %>
Your browser is <%= Bobj.browser %> <%= Bobj.majorver %>.<%= Bobj.minorver %>
running on a <%= Bobj.platform %> Operating System. <BR>
<!-- sometimes the browsercap.ini file may not have all the necessary info
In this case a value of "Unknown" is returned -->
Browser, Operating System as determined from HTTP_USER_AGENT=
<%= Request.ServerVariables("HTTP_USER_AGENT") %>
</FORM>
<% else
dim LC(3)
LC(0) = 1033 : LC(1) = 2057 : LC(2)=1036
Session.LCID = LC(CInt(Request("optStyle")))
end if
%>
Current Date and Time = <%= Now %>
</BODY>
</HTML>
Example:
First set some cookies by viewing the Serversc29a.asp file as shown
below, then view the Serversc29.asp file which will print the values of all
cookies.
<% @LANGUAGE = VBScript %>
<% 'Serversc29a.asp
Response.Buffer=True %>
<HTML>
</HEAD>
<TITLE> Setting some session cookies </TITLE>
</HEAD>
<BODY>
Setting some session cookies
<%
Response.Cookies("User")("Name")="Mahmood"
Response.Cookies("User")("FavCookie")="OatMeal Raisin"
Response.Cookies("User")("ID")="9876"
' ----- a cookie without keys
Response.Cookies("Color") = Blue
%>
</BODY>
</HTML>
<%
Dim CK, key
For Each CK In Request.Cookies
If Not Request.Cookies(CK).HasKeys Then
Response.write "Simple cookie and its value : "
Response.Write CK & " = " & Request.Cookies(CK) & "<br>"
Else
For Each key In Request.Cookies(CK)
Response.Write CK
Response.Write "(" & key & ")"
Response.Write " = "
Response.Write Request.Cookies(CK)(key)
Response.Write "<br>" & vbCrLf
Next
End If
Next
%>
</BODY>
</HTML>
Example:
<% @LANGUAGE = VBScript %>
<% 'Serversc30.asp %>
<HTML>
</HEAD>
<TITLE> Test of HTMLEncoding </TITLE>
</HEAD>
173
<BODY>
<% dim s1
s1 = "My age is <Fred but> Amy" %>
Here is the value of a string that has some special characters <BR>
Without HTML Encoding: <I> <% = s1 %> </I>
<BR>
<% dim s2
s2 = Server.HtmlEncode(s1) %>
Now after html encoding, the same string appears as: <BR>
With Html Encoding: <I> <% =s2 %> </I>
<BR>
Some times we can use the HTML codes ourselves to specify a string for
display in the browser e.g., My age is <Fred but> Jerrine.
<BR>
We can also use the ASCII codes for special characters, e.g., <BR>
The current temperature is 75°
</BODY>
</HTML>
Example: Suppose a telephone number lookup site has a search page that
looks like:
<% @LANGUAGE = VBScript %>
<% 'Serversc31.asp %>
<HTML>
</HEAD>
<TITLE> Test of URLEncoding - A Page which accepts a form </TITLE>
</HEAD>
<BODY>
<% If Request.ServerVariables("QUERY_STRING")="" Then %>
<FORM method=get action="<%=Request.ServerVariables("SCRIPT_NAME")%>">
Please Enter Company name: <INPUT NAME=txtName SIZE=15>
<INPUT TYPE=SUBMIT NAME=cmdSubmit>
<HR>
<% else
dim s1, Phone
s1 = Request("txtName")
If s1 = "D & D Motors" Then Phone="512-4595" else Phone="Not Found"
Response.write "Company Name = " & s1 & " Phone Number = " & Phone
end if %>
</BODY>
</HTML>
You can test the above page by opening it in your browser and typing in a
company name of D & D Motors to see if it is able to return the phone
number of the company correctly.
174
Now let us try to access this telephone lookup page through another page by
preparing the query string and redirecting to this page as shown below:
<% @LANGUAGE = VBScript %>
<% 'Serversc31a.asp
Response.buffer=True %>
<HTML>
</HEAD>
<TITLE> Test of URLEncoding - Submitting Query to another Page </TITLE>
</HEAD>
<BODY>
<% dim s1, ID
s1 = "http://mango/HTMLEx/Serversc31.asp?txtName="
s1 = s1 & "D & D Motors"
Response.redirect s1
%>
</BODY>
</HTML>
If you open the page Serversc31a.asp, you will get the following output
Note that the problem is the query string prepared in Serversc31a.asp. The
query string uses & to separate the parameters and + sign for a space. You
can verify this by opening the Serversc31.asp page directly and submitting a
query.
The correct solution is to UrlEncode the string (especially if the string has &
character or spaces) before attaching it to the query string.
Change the line in Serversc31a.asp
s1 = s1 & "D & D Motors"
to
s1 = s1 & Server.UrlEncode("D & D Motors")
Now if you view the Serversc31a.asp in your browser, it will work correctly.
Example:
<% @LANGUAGE = VBScript %>
<% 'Serversc32.asp
Response.buffer=True %>
<HTML>
</HEAD>
<TITLE> Submitting Search Requests to Other Engines </TITLE>
</HEAD>
<BODY>
<% If Request.ServerVariables("QUERY_STRING")="" Then %>
Search Form: <BR>
<FORM method=get action="<%=Request.ServerVariables("SCRIPT_NAME")%>">
Please Enter Search String: <INPUT NAME=txtSearch SIZE=40>
<INPUT TYPE=SUBMIT NAME=cmdSubmitYahoo Value="Search Yahoo">
<INPUT TYPE=SUBMIT NAME=cmdSubmitExcite Value="Search Excite">
<HR>
<% else
dim s1, b1, qs
s1 = Request("txtSearch")
b1 = Request("cmdSubmitYahoo")
b2 = Request("cmdSubmitExcite")
If b1 = "Search Yahoo" Then
qs = "http://search.yahoo.com/bin/search?p="
qs = qs & Server.UrlEncode(s1)
Response.redirect qs
end if
If b2 = "Search Excite" Then
qs = "http://search.excite.com/search.gw?search="
qs = qs & Server.UrlEncode(s1)
Response.redirect qs
end if
end if %>
</BODY>
</HTML>
The two columns in the table of contents text file should be separated
by tabs. The first column is the actual page file name while the second
column is a brief description of the page file.
Example: The table of contents text file for PQR corporation might look as
shown below (the file is saved as PQRTableContents.txt):
GetListCount Number of items i.e., rows in the table of contents text file
GetListIndex Index of the current page in the table of contents text file. A 0 is returned if the
page is not listed in the table of contents text file.
GetPreviousURL Page file name of previous row so that a link to previous page can be determined
GetNthURL, GetNthDescription returns info about the Nth row in the table of contents file.
Example: Main page for PQR corporation generates the table of contents
automatically by using the MSWC.NextLink component.
<% 'PQRMainPage.asp %>
<HTML>
<HEAD>
<TITLE> Main Page for PQR Corp. </TITLE>
</HEAD>
<BODY>
<H3> Main Page for PQR Corporation <H3>
Generating Table of Contents Using MSWC.NextLink ActiveX component
<HR>
<UL> <!-- Generate an unordered list of contents -->
<%
dim Lcomp, lcount, i
Set Lcomp = Server.CreateObject("MSWC.NextLink")
lcount = Lcomp.GetListCount("PQRTableContents.txt")
177
For i = 1 to lcount
%>
<LI> <A HREF="<%=Lcomp.GetNthURL("PQRTableContents.txt",i) %>">
<%= Lcomp.GetNthDescription("PQRTableContents.txt",i) %> </A>
<% Next %>
</UL>
</BODY>
</HTML>
' Second page and onwards should point to the previous page
If (currentindexnum > 1) Then 'it exists in the table of contents file
Response.write "<A HREF=""" & Lcomp.GetPreviousURL("PQRTableContents.txt")
Response.write """> Previous Page </A>"
both = 1
End If
' Except for the last page, each page should point to next page
If (currentindexnum <> Lcomp.GetListCount("PQRTableContents.txt")) Then
If both = 1 Then Response.write "<BR>"
Response.write "<A HREF=""" & Lcomp.GetNextURL("PQRTableContents.txt")
Response.write """> Next Page </A>"
End If
%>
Each of the pages in the company will include the above file to determine
the next and previous links as shown below.
<!-- PQRFirst.asp -->
<HTML>
<HEAD>
<TITLE> First Page for PQR Corp. </TITLE>
</HEAD>
<BODY>
<H3> First Page for PQR Corporation <H3>
<!-- #include file="PQRTabCont.inc" -->
</BODY>
</HTML>
</HEAD>
<BODY>
<H3> Second Page for PQR Corporation <H3>
<!-- #include file="PQRTabCont.inc" -->
</BODY>
</HTML>
<!-- PQRThird.asp -->
<HTML>
<HEAD>
<TITLE> Third Page for PQR Corp. </TITLE>
</HEAD>
<BODY>
<H3> Third Page for PQR Corporation <H3>
<!-- #include file="PQRTabCont.inc" -->
</BODY>
</HTML>
Exercise: Try adding a file PQRSecondA.asp and see if the table of contents and
all other links are adjusted correctly.
Accessing Files on the Server:
Note that exact path names are needed when opening a file on the
server i.e., we cannot use virtual path names. Server.MapPath(“filename”)
becomes very useful in obtaining the complete path name. It will
automatically obtain the physical directory path corresponding to the virtual
directory the script is written in.
Example:
<% @LANGUAGE = VBScript %>
<% 'Serversc33.asp %>
<HTML>
</HEAD>
<TITLE> Reading/Writing Text Files on the Server </TITLE>
</HEAD>
<BODY>
<%
Const ForReading = 1, ForWriting = 2, ForAppending = 8
dim fSObj, textSObj, fname
Set fSObj = Server.CreateObject("Scripting.FileSystemObject")
fname = Server.MapPath("testfile.dat") 'obtain full path name
'Response.write fname
If fSObj.FileExists(fname) = True Then
Set textSObj = fSObj.OpenTextFile(fname, ForAppending, False, 0)
'False means do not create if file does not exist, 0 means ASCII file
Else
Set textSObj = fSObj.CreateTextFile(fname, False, False)
' False means do not overwrite if file exists, last False means ASCII
End If
'read and print the registered users and passwords from registeredusers.txt file
Response.write "<BR>" & "<HR>"
fname = Server.MapPath("registeredusers.txt")
Response.Write "Following data read from the file " & fname & "<HR>"
Set textSObj = fSObj.OpenTextFile(fname, ForReading, 0)
dim userpw
while textSObj.AtEndOfStream <> True
strLine = textSObj.ReadLine
userpw = split(strLine,chr(9))
Response.write userpw(0) & " " & userpw(1) & "<BR>" & VbCrLf
wend
textSObj.close
Set textSObj = nothing
Set fSObj = nothing
%>
</BODY>
</HTML>