Sie sind auf Seite 1von 46

135

Active Server Pages


• Active Server Pages (ASP) is an object-based server-side
scripting environment.
• Both VBScript and JavaScript can be used for server-side
scripting under ASP. However, the preferred language for
server-side scripting is usually VBScript.
• Client-side and server-side scripting code can be used within
the same page.
• There are six built-in ASP objects that simplify web
development. These are:
Application
ObjectContext
Request
Response
Server
Session

Part of learning ASP is to understand the properties, methods and events of


the above objects and to effectively use them inside a script code.

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

It is a good practice to identify the server-side scripting language for each


page by including a statement at the top of the page as shown below:
<% @ LANGUAGE=VBScript %>

The server-side scripting language can be changed for functions/subs within


a page by using the SCRIPT tag along with RUNAT=SERVER
identification.

<SCRIPT LANGUAGE=JavaScript RUNAT=SERVER>


…..
……
</SCRIPT>

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.

<!-- Serversc1.htm -->


<% @ 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>

Conclusion: A file containing server-side script code must have


the extension .asp.

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:

Response.write "<BR>" & t1

<%= variable or expression %> replaces the value of variable or


expression and sends it to the browser.

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

<% Response.expires=0 %>


<!-- Serversc5.asp -->

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.expires=60 page expires in 60 minutes

Response.ExpiresAbsolute=#6/1/2000 06:30:00#

Or

Response.ExpiresAbsolute=#June 1, 2000 06:30:00#

<SCRIPT RUNAT=SERVER> tag is used to define a function or sub that


will be executed on the web server. This tag is particulary useful in mixing
different scripting languages on the server.

Example: Change the Serversc5.asp file as shown below.


<% @ LANGUAGE=VBScript%>
<% Response.expires=0 %>
<!-- Serversc6.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>
<SCRIPT LANGUAGE=VBSCRIPT RUNAT=SERVER>
dim t1
t1 = now
</SCRIPT>
<H3> <CENTER> Date and Time on the server = <%= t1 %>
</CENTER></H3>
<HR>
</BODY>
</HTML>

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

<% Response.expires=0 %>


<!-- Serversc7.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>
<SCRIPT LANGUAGE=VBSCRIPT RUNAT=SERVER>
Function ServerDateTime()
dim t1
t1 = now
ServerDateTime = t1
End Function
</SCRIPT>
<H3> <CENTER> Date and Time on the server = <%= ServerDateTime %>
</CENTER></H3>
<HR>
</BODY>
</HTML>

Conclusion: <SCRIPT LANGUAGE=VBSCRIPT RUNAT=SERVER>


should be used to identify server-side functions and subs.
Example of mixing Server-side scripting languages:
<% @ LANGUAGE=VBScript %>
<% Response.expires=0 %>
<!-- Serversc8.asp -->
<HTML>
<HEAD>
<TITLE> Server side scripting - Mixing Languages </TITLE>
</HEAD>
<BODY>
<SCRIPT LANGUAGE=VBSCRIPT RUNAT=SERVER>
Function ServerDateVBS()
dim t1
t1 = now
ServerDateVBS = t1
End Function
</SCRIPT>

<SCRIPT LANGUAGE=JAVASCRIPT RUNAT=SERVER>


function ServerDateJS() {
var t1;
t1 = new Date();
return t1;
}
</SCRIPT>
<H3> Date and Time on the server (VBS function) = <% =ServerDateVBS %> </H3>
<HR>
<H3> Date and Time on the server (Javascript function) = <%= ServerDateJS() %> </H3>
</BODY>
</HTML>
142

Server-side Includes – reusable code blocks


When a web site involves quite a bit of script code, it is always a good
idea to break the program into several files. Commonly used functions and
subs can be placed in a file and this file can be included where ever these
functions/subs are needed.
<!--#INCLUDE FILE=filename --> or <!--#INCLUDE VIRTUAL=filename -->
Virtual indicates the file relative to the virtual web server directory.
Example: Create a function called greeting and place it in the greet.inc file
in the include subdirectory as shown below.
<!-- greet.inc.txt -->
<SCRIPT LANGUAGE=VBSCRIPT RUNAT=SERVER>
Function greeting()
dim t1, strMsg
t1 = now
If Hour(t1) < 12 Then
strMsg="Good Morning"
ElseIf Hour(t1) < 18 Then
strMsg="Good Afternoon"
Else
strMsg = "Good Evening"
End If
greeting = strMsg
End Function
</SCRIPT>

<% @ LANGUAGE=VBScript %>


<% Response.expires=0 %>
<!-- Serversc9.asp -->
<HTML>
<HEAD>
<TITLE> Server side scripting - Server-side Includes </TITLE>
</HEAD>
<BODY bgcolor="aqua">
<!-- #INCLUDE FILE="include/greet.inc.txt" -->
Greetings from the server:
<FONT FACE="Comic Sans MS" SIZE=6 COLOR="#FF00FF">
<%= greeting %>
</FONT>
<HR>
</BODY>
</HTML>

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.

Conclusion: All INCLUDE files should have the extension .asp.


Rename the greet.inc.txt file to greet.asp and also make the corresponding
change in the Serversc9.asp file as:
<!-- #INCLUDE FILE="include/greet.asp" -->

Now the client browser cannot see the code in the greet.asp file even if this
file is viewed in the browser directly.

Exercise: Try the INCLUDE VIRTUAL option as:


<!-- #INCLUDE VIRTUAL="MyWeb/include/greet.asp" -->

In the INCLUDE FILE=./ corresponds to current directory,


INCLUDE FILE=../ corresponds to the parent directory relative to the
current directory of the file.

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

<!-- Serversc10.asp -->


<HTML>
<HEAD>
<TITLE> Server side scripting - Date and Time on the Server </TITLE>
</HEAD>
<BODY>
<H2> <CENTER> Server Side Scripting </CENTER> </H2>
<%
dim t1
t1 = now
%>
<H3> This part of the page is not cached </H3>
<H3> <CENTER> Date and Time on the server = <%= t1 %>
</CENTER></H3>
<HR>
This is an image file which will be cached for some time:
<SCRIPT LANGUAGE=JAVASCRIPT SRC="IMG.asp">
</SCRIPT>
</BODY>
</HTML>

<% Response.expires=1 %>


<!-- IMG.asp -->
document.writeln(" Time at which image sent from server = <%=time%>");
document.writeln('<IMG SRC="yahoocard.gif" BORDER=0>');
145

Setting Page expiration relative to current time on the server.


Example:
<% @ LANGUAGE=VBScript%>
<%
dim exp1
exp1 = DateAdd("n",1,now) 'n specifies minutes, m specifies month
Response.ExpiresAbsolute=exp1
%>
<!-- Serversc11.asp -->
<HTML>
<HEAD>
<TITLE> Server side scripting - Setting page expiration relative to current time </TITLE>
</HEAD>
<BODY>
<H2> <CENTER> Server Side Scripting </CENTER> </H2>
<SCRIPT LANGUAGE=VBSCRIPT RUNAT=SERVER>
Function ServerDateTime()
dim t1
t1 = now
ServerDateTime = t1
End Function
</SCRIPT>
<H3> <CENTER> Date and Time on the server = <% Response.write(ServerDateTime()) %>
</CENTER></H3>
<HR>
<% Response.write("Page Expiration set at: " & exp1) %>
</BODY>
</HTML>

Redirecting to another Page


We can use the Response.redirect method to redirect the user to another
page. This is needed quite often when the web site location changes or after
the user accesses a page that requires log-in, the user will be redirected to the
log-in page.
The Response.redirect is part of the header and thus requires that no
HTML output has been written to the page.
Example:
<% @ LANGUAGE=VBScript%>
<%
Response.expires=20 '20 minute expiration
If Hour(now) > 12 Then
Response.redirect "serversc10.asp"
else
Response.redirect "http://www.amazon.com"
end if
%>
<!-- Serversc12.asp -->
146

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

Example: Use of flush, clear and end methods of Response object


<% @ LANGUAGE=VBScript%>
<%
Response.buffer=True
Response.expires=1 '1 minute expiration
%>
<!-- Serversc14.asp -->
<HTML>
<HEAD>
<TITLE> Server side scripting - Response.redirect method </TITLE>
</HEAD>
<BODY>
<H2> <CENTER> Server Side Scripting - Response.redirect </CENTER> </H2>
<%
if Hour(Now) < 12 Then 'Try changing the "<" to ">"
Response.write ("Server time = " & Now & "<BR>")
Response.write "We are flushing the output so far and ending response"
Response.flush
Response.end 'no further output will be sent
'actually Response.end flushes the output also
else
Response.clear 'all previous output is cancelled
Response.expires=0
Response.write("This content expires quickly")
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

NOTE: ContentType should be set before sending any content to the


browser i.e., it is a header specification.

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
%>

<H1>Welcome to My Musical Page.</H1>


I enjoy developing Web Applications Using ASP.
ASP has several COM based prebuilt objects that
can be used in a scripting language such as VBscript,
or Javascript, or Perlscript etc..

ASP is easy to learn and you can create very useful Web
applications relatively quickly, with it

Try changing the line Response.ContentType="text/plain" to


Response.ContentType=”text/html” and then view it in the browser.
Try changing the ContentType to “application/msword” and view it in the
browser.

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

Request.ServerVariables(“HTTP_headername”) returns the value of a


particular HTTP header e.g.,

Request. ServerVariables(“HTTP_USER_AGENT”) returns the browser


name and platform on which it is running.
Request. ServerVariables(“HTTP_REFERER”) returns the url of the web
page that invoked this asp page.

Request. ServerVariables(“REMOTE_ADDR”) returns the client’s IP


address.

You can determine all HTTP headers sent from the browser by executing the
following code:

<%= Replace(Request. ServerVariables(“ALL_RAW”), vbCrLf,”<BR>”) %>

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)

strClientIP = Request. ServerVariables("REMOTE_ADDR")


Response.write("<BR>Client browser machine's IP address is: " & strClientIP)
%>
<HR>
</BODY>
</HTML>

GET and POST methods for Submitting Forms to the Server:


GET method:
150

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

The value of querystring can be determined by:


Request.ServerVariables(“QUERY_STRING”)

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>

<% @LANGUAGE=VBSCRIPT %>


<% 'Serversc17a.asp %>
<HTML>
<HEAD>
<TITLE> Reading the Query String</TITLE>
</HEAD>
<BODY>
<H2> User ID and Password </H2>
<HR>
<%
Response.write("UserID submitted = " & Request.querystring("USERID"))
Response.write("<BR>Password submitted = " & Request.querystring("PASSWORD"))
%>
</BODY>
</HTML>
151

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

<% 'Serversc19.asp %>


<HTML>
<HEAD>
<TITLE> POST method to Submit a FORM</TITLE>
</HEAD>
<BODY>
<H2> Web Site Feedback </H2>
<HR>
<% If Request.ServerVariables("CONTENT_LENGTH") = 0 Then %>
<H3> Please Enter Name, UserID and some Comments </H3>
<FORM method=POST ACTION= "<%=Request.ServerVariables("SCRIPT_NAME")%>">
<PRE>
Name: <INPUT NAME="txtName" SIZE="20" MAXLENGTH="20" VALUE="">
User ID: <INPUT NAME="txtID" SIZE="10" MAXLENGTH="10" VALUE="">

Comments: <TEXTAREA NAME=txaComments ROWS=5 COLS=40></TEXTAREA>


<INPUT TYPE=SUBMIT VALUE="Submit Post Form" NAME=cmdSubmit>
<HR>
</PRE>
</FORM>
<% Else
Response.write("Name submitted = " & Request.Form("txtName"))
Response.write("<BR>User ID submitted = " & Request.Form("txtID"))
strComm = Replace(Request.Form("txaComments"),vbcrlf,"<BR>")
Response.write("<BR>" & strComm)
End If
%>
</BODY>
</HTML>

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

Name: <INPUT NAME="txtName" SIZE="20" MAXLENGTH="20" VALUE="">


User ID: <INPUT NAME="txtID" SIZE="10" MAXLENGTH="10" VALUE="">

Comments: <TEXTAREA NAME=txaComments ROWS=5 COLS=40></TEXTAREA>


<INPUT TYPE=SUBMIT VALUE="Submit Post Form" NAME="cmdSubmit">
<HR>
</PRE>
</FORM>
<% Else
Response.write("Name submitted = " & Request.Form("txtName"))
Response.write("<BR>User ID submitted = " & Request.Form("txtID"))
strComm = Replace(Request.Form("txaComments"),vbcrlf,"<BR>")
Response.write("<BR>" & strComm)
End If %>
</BODY>
</HTML>
Application Object, Global.asa, Session Variables and
Program-Based Security
Consider a hypothetical company called XYZ corporation. The main page of
XYZ corporation might look like:
<!-- 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.htm"> Salaries of Employees (password protected) </A>
<BR> <BR>
<A HREF="news.htm"> Current News about XYZ Corporation </A>
</BODY>
</HTML>

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>

<!-- Salaries.htm -->


154

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

<INPUT TYPE=SUBMIT VALUE="Submit Name & Password" NAME=cmdLogin>


<HR>
</PRE>
</FORM>
<% else %>
<!-- #include FILE="authenticateUser.asp" -->
<% end If %>
<H2> Main Page - Welcome to XYZ Corporation </H1>
<H2> Important Links </H2>
<BR>
<A HREF="salaries.htm"> Salaries of Employees (password protected) </A>
<BR> <BR>
<A HREF="news.htm"> Current News about XYZ Corporation </A>
155

</BODY>
</HTML>
<% 'AuthenticateUser.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"))

'Call subs and functions to perform proper login verification


ReportLoginStatus(VerifyLogin) 'either correct login or incorrect password attempt

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

Problem with the above Solution:


1. Non-registered users cannot see any page in the site. Often we want to
protect only a selected set of pages with passwords.
2. A user can actually bypass the login page (indexa.asp) and directly go
to salaries.htm, for example).

We will devise a better and secure solution.


The modified web application is divided into the following important files:
1. Index.htm default page for XYZ corporation
2. FormLogin.asp prompts the user for username and password
3. AuthenticateUsera.asp verifies username and password by checking
registration file.
4. ProtectbyPass.asp an SSI include file that can be added to any page
which needs to be secured with a password.
5. RegisteredUsers.txt List of registered users and their passwords
6. news.htm company news about XYZ corporation
7. salaries.asp Salaries of Employees in XYZ corporation
(protected by password)
8. empreviews.asp Employee reviews for 1999 (needs to be password
protected)

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

<INPUT TYPE=SUBMIT VALUE="Submit Name & Password" NAME=cmdLogin>


<HR>
</PRE>
</FORM>
</BODY>
</HTML>

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

'Call subs and functions to perform proper login verification


ReportLoginStatus(VerifyLogin) 'either correct login or incorrect password attempt

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

'This file should be included in each page that needs password


'protection
dim strRequestURL
strRequestURL = "http://" & Request.ServerVariables("SERVER_NAME")
strRequestURL = strRequestURL & Request.ServerVariables("PATH_INFO")
If Session.Contents("Username") = "" Then
Session.Contents("RequestedURL") = strRequestURL
Response.Redirect "FormLogin.asp"
End If
%>
159

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>

Exercise: Add Password protection to EmpReviews.asp file

Logging Out – Clearing session variables


Use the abandon method of the session object to logout from a secured page.
Example: Add a logout option in the salaries.asp file.
Logout.asp:
<% 'logout.asp %>
<%
Session.abandon
Response.redirect "index.htm" 'back to main page
%>

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>

• You can store information in Session object only if the browser


supports Cookies or if the support for cookies has not been
turned off.
161

• When a browser is started, a unique Session ID is created and


stored in the browser as a session cookie. This session ID is
submitted automatically to the web server on each request.
• The session values stored in the session object are unique for
each user and cannot be shared between different users
(clients).
• If sharing of information is needed between different users,
then use the Application object to create truly global variables.
• The application level variables should be protected by Lock
and Unlock methods when modifications are needed.
• Global.asa file is used to provide the start and end events for
the application and session objects.

Example: Tracking page hits of a certain page


<% @LANGUAGE=VBSCRIPT %>
<% 'Serversc21.asp %>
<% Option explicit
dim strPageHitCount 'creating a unique application variable for page
strPageHitCount = "HitCount" & Request.ServerVariables("SCRIPT_NAME")
%>
<HTML>
<TITLE> Page count Test </TITLE>
<BODY>
<H3> Test of Page Hit Count </H3>
<HR>
<%
Application.Lock 'protect shared veriables from simultaneous update
If IsEmpty(Application(strPageHitCount)) Then
Application(strPageHitCount) = 0
End If
Application(strPageHitCount) = Application(strPageHitCount) + 1
Application.Unlock
%>
Page Hits = <%= Application(strPageHitCount) %>
<% Response.write "<BR>Application variable name for Page hit Counts = " & _
strPageHitCount
%>
</BODY> </HTML>
Keeping Count of all hits of an application:
<% @LANGUAGE=VBSCRIPT %>
<% 'Serversc22.asp %>
<%
Application.lock 'These three lines should be placed in each page
Application("AllPageHitsCount") = Application("AllPageHitsCount") + 1
Application.Unlock
%>
<HTML>
<TITLE> All Page hit count Test </TITLE>
162

<BODY>
<H3> Test of All Page Hit Count </H3>
<HR>
All Page Hits = <%= Application(“AllPageHitsCount”) %>
</BODY>
</HTML>

Modified global.asa file:


<SCRIPT LANGUAGE=VBSCRIPT RUNAT=SERVER>

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>

Keeping Count of all Page hits during a single session:


<% @LANGUAGE=VBSCRIPT %>
<% 'Serversc23.asp %>
<% 'add the following line to each page in the application
Session("AllSessionHits") = Session("AllSessionHits") + 1
%>
<HTML>
<TITLE> All Page hit count Test </TITLE>
<BODY>
<H3> All Page Hits within a Session </H3>
<HR>
All Page Hits in this Session = <%= Session("AllSessionHits") %>
</BODY>
</HTML>

Modified Global.asa file:


<SCRIPT LANGUAGE=VBSCRIPT RUNAT=SERVER>

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>

Count of Number of Currently Connected Users to the App.


<% @LANGUAGE=VBSCRIPT %>
<% 'Serversc24.asp %>
<% 'add the following line to each page in the application
Session("AllSessionHits") = Session("AllSessionHits") + 1
%>
<HTML>
<TITLE> All Page hit count Test </TITLE>
<BODY>
<H3> All Page Hits within a Session </H3>
<HR>
All Page Hits in this Session = <%= Session("AllSessionHits") %>
<BR>
Number of Users currently connected to this application :
<%= Application("CurrentUserCount") %>
<BR>
Number of Total Users so Far who have used this application :
<%= Application("AllUserCount") %>
</BODY>
</HTML>
Modified Global.asa file:
<SCRIPT LANGUAGE=VBSCRIPT RUNAT=SERVER>

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.

NOTE: The expiration time of a cookie is very important. If no expiration


is specified, the cookie defaults to a session cookie.
The cookies are stored in a simple text file on the Client machine e.g., on a
windows 95/98 machine it is in the windows/cookies directory.

A dictionary of Cookies can be created to store related information under a


single cookie name.
Example:
Response.Cookies(“User”)(“Username”) = “mahmood”
Response.Cookies(“User”)(“Password”) = “mango55”
Response.Cookies(“User”).Expires=DateAdd(“m”,1,”Now)

The value of a cookie can be retrieved by ASP code by identifying the


cookie name from the Request object e.g.,
Uname = Request.Cookies(“User”)(“Username”)

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

Determining if Cookies are Enabled on the Browser

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

Sometimes it may be necessary to determine if the browser’s setting


for accepting session cookies is turned on or off. One way, this can be
accomplished is by creating a session variable and then reinvoking the same
page to see if the session variable was stored successfully or not.

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>

Another Approach to testing if Cookies and/or Javascript is


enabled on the Browser.
This technique does not require a page to be called twice. It uses client-side
Javascript code to determine if a cookie was successfully stored in the
browser or not.
Example:
<% @LANGUAGE = VBScript %>
<% 'Serversc26.asp
Option Explicit
Const ErrorDocument = "Serversc26err.asp"
Const CookieName = "TestCookie"
Response.Cookies(CookieName) = 1
%>
<HTML>
<HEAD>
<TITLE> Client-side approach to Cookie Testing </TITLE>
<SCRIPT language="javascript">
<!--
var cookieStartIndex = document.cookie.indexOf('<%=CookieName & "="%>');
if (cookieStartIndex == -1)
document.location.href="<%=ErrorDocument%>";
-->
</SCRIPT>
<noscript>
<META http-equiv="Refresh" content="<%=ErrorDocument%>?err=js">
</noscript>
<title>Cookie Testing Script</title>
</HEAD>
<BODY bgcolor=#ffff00>
169

Cookies and JavaScript are enabled in your Browser.


</BODY>
</HTML>
<% @LANGUAGE = VBScript %>
<% 'Serversc26err.asp
Option Explicit
Dim strError, strErrorMessage
strError = Trim(Request.QueryString("err"))
If "1" = Request.Cookies("TestCookie") Then
' JavaScript disabled, but Cookies are enabled
strErrorMessage = "JavaScript is not enabled on your browser! Cookies are supported."
ElseIf "js" = strError Then
' JavaScript is disabled and Cookies too
strErrorMessage = "JavaScript and Cookies are disabled on your browser."
Else : strErrorMessage = "Cookies are not enabled on your browser."
End If %>
<html>
<head>
<title>Cookie Enabling Error</title>
</head>
<body bgcolor=#ffffff>
<%=strErrorMessage%>
</body>
</html>
To see if a Browser Type Supports Cookies, VBScript, ActiveX
components etc..:
When a browser submits a page request to the web server, it identifies its
attributes via the Request.ServerVariables(“HTTP_USER_AGENT”) object.
However, while this may identify the browser type, the platform OS etc.., it
does not indicate whether the browser supports VBScript, Javascript,
ActiveX controls, frames, cookies etc..
One way to determine the above capabilities is by using the ActiveX
component called “MSWC.BrowserType”. This component takes the
information from the HTTP_USER_AGENT (i.e., browser name, version)
and compares it with the information stored in a file called browsercap.ini
which exists in the windows/InetSrv directory in a windows95/98 computer.

To get a better idea of what is stored in the browsercap.ini file, examine it in


your computer.

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") %>

<% If Not (Bobj.Cookies = "True") Then %>


Your browser does not support Cookies. However to use our site you need
a browser with cookie capabilities.
<% elseif Not (Bobj.vbscript = "True") Then %>
Your browser does not support VBScript. However to use our site you need
a browser with VBScript capabilities.
<% else %>
<BR> <BR>Welcome Your browser supports Cookies and
Vbscript ... The current Date and Time is <%= Now %>
<% end if %>
</BODY>
</HTML>

Setting the Locale ID using the Session Object:


<% @ LANGUAGE=VBScript%>
<% Response.expires=0 %>
<!-- Serversc28.asp -->
<HTML>
<HEAD>
<TITLE> Locale ID Example </TITLE>
</HEAD>
<BODY>
<H2> <CENTER> Locale ID example </CENTER> </H2>
<% If Request.ServerVariables("QUERY_STRING") = "" Then
dim lang
lang = Request.ServerVariables("HTTP_ACCEPT_LANGUAGE")%>
Your browser has the preferred language as : <%= lang %> i.e.,
<% ' LA-CO where CO is country e.g., en-us, fr for French, us for USA
If lang = "en-us" Then Response.write "English-USA <BR>"
If lang = "en-gb" Then Response.write "English-UK <BR>"
If lang = "fr" Then Response.write "French <BR>"
%>
Please choose your preference for viewing date and Time Information:
<FORM METHOD=GET ACTION="<%=Request.ServerVariables("SCRIPT_NAME")%>">
<INPUT TYPE=RADIO NAME=optStyle VALUE=0 checked> USA
<INPUT TYPE=RADIO NAME=optStyle VALUE=1> English
<INPUT TYPE=RADIO NAME=optStyle VALUE=2> French
<BR>
<INPUT TYPE=SUBMIT VALUE="Choose Date Formatting">
171

</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>

Examining dictionary and non-dictionary cookies:


A dictionary cookie can be examined by checking its HasKeys
property.

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>

<% @LANGUAGE = VBScript %>


<% 'Serversc29.asp
Option Explicit %>
<HTML>
<HEAD>
<TITLE> Reporting Cookies - HasKeys Property </TITLE>
</HEAD>
<BODY>
Reporting the Values of Cookies - both single cookies and dictionary
cookies are examined using the Haskeys property <BR>
172

<%
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>

HTML-Encoding, URL-Encoding Strings:


There are two useful methods of the Server object
“Server.HtmlEncode(..)” and Server.UrlEncode(..) that are very useful in
encoding strings for displaying of special characters in a web page
(HtmlEncode) and for preparing query strings (UrlEncode) in submitting
requests to a web site.
For example, if a string contained in a field in a database has special
characters (e.g., o), it should be HtmlEncoded before sending it to the
browser, otherwise the o will not be displayed correctly.
Similarly if a string contained < or > sign, it will not be displayed
properly in the browser unless HtmlEncoded.
Some popular HTML codes are: &nbsp, &lt, &gt, &quot
We can also use the ASCII codes for special characters, e.g., #169 is the
ASCII code for copyright sign, #214 for umlaut mark, #174 for registered
mark, #176 for degree sign (temperature) etc..
For example: Response.write “The current temperatures is 75&#176”

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 &ltFred but&gt Jerrine.
<BR>
We can also use the ASCII codes for special characters, e.g., <BR>
The current temperature is 75&#176

</BODY>
</HTML>

URL Encoding is mostly used in preparing query strings.

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.

Submitting Queries to Other Search Engines through your own


page:
Open the yahoo site and submit a search, then examine the query string. You
can also take a look at the source (view->source from the menu) to find out
the name of the text box. Do the same for excite. Then prepare a simple
search form with two buttons that will allow you to submit a search either to
yahoo or excite search engines:
175

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>

Generating an automatic Table of Contents and linking by


Using MSWC.NextLink ActiveX component
MSWC.NextLink ActiveX component is very useful in creating a table of
contents from a simple text file. It can also be used to link individual pages
to their previous and next page as specified in the table of contents text file.
176

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):

PQRFirst.asp First Page in Table of Contents


PQRSecond.asp Second Page in Table of Contents
PQRThird.asp Third Page in Table of Contents

Important methods of the MSWC.NextLink component are listed below:

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

GetPreviousDescription Page description of previous row to create a hyperlink to previous page.

GetNextURL, GetNextDescription similar to GetPreviousURL and description except it returns


the next row to determine the next link to the current page.

GetNthURL, GetNthDescription returns info about the Nth row in the table of contents file.

MSWC.NextLink component can be used in the main page of the company


to generate the table of contents as demonstrated by the example below:

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>

An include file as shown below can be created to be put in each page in


which we may want to determine the next link and/or the previous link.

<% 'PQRTabCont.inc %>


<%
dim Lcomp, currentindexnum, both
both = 0
Set Lcomp = Server.CreateObject("MSWC.NextLink")
currentindexnum = Lcomp.GetListIndex("PQRTableContents.txt")

' 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>

<!-- PQRSecond.asp -->


<HTML>
<HEAD>
<TITLE> Second Page for PQR Corp. </TITLE>
178

</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:

ASP provides an ActiveX component called “Scripting.FileSystemObject”


for accessing files, folders and drives on the server.
179

Scripting.FileSystemObject provides a few important methods to


create files, open existing files for reading or writing e.g., CreateTextFile
and OpenTextFile methods. These methods end up creating an object called
TextStream object which has several methods for reading or writing data to a
file e.g., Read, ReadLine, ReadAll, Write, Writeln, Close.

TextStream object provides two important properties to determine the


end of line or end of file when reading data from a file (AtEndOfLine,
AtEndOfStream).

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

textSObj.WriteLine "This line added to the file at " & Now


textSObj.Close
'Now let us open the same file and display its contents to the page.
Set textSObj = fSObj.OpenTextFile(fname, ForReading, 0)
dim strLine
Response.Write "Following data read from the file " & fname
Response.write "<HR>"
do while textSObj.AtEndOfStream <> True
strLine = textSObj.ReadLine
strLine = Server.HTMLEncode(strLine) 'In case there are special characters
180

Response.write strLine & "<BR>" & VbCrLf


Loop
textSObj.close

'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>

Das könnte Ihnen auch gefallen