Está en la página 1de 191

INTERNET PROGRAMMING AND WEB TECHNOLOGY

Unit I
What is the computer network?
The computer network is the communication of data from one computer to one or
more computers by any means such as people, wires, cables, or a telecommunications
system.
A local area network (LAN) is the communication of a number of computers by
cable connecting to each one in a single location, usually a single floor of a building or all
the computers in a small company. LANs may be contrasted with wide area networks
(WANs). Stated simply, WANs are the communication between LANs by telephone lines
leased form the various telephone companies, satellite links, packet radio, or microwave
transceivers.
WANs are private and owned by the business that operates with them. The
Internet has emerged as both the largest and the least expensive WAN in the world
recently. Many companies take advantage of it now by forming private WANs, known as
VPNs, or Virtual Private Networks, through encrypted communications over the Internet.

Network Type
There are three roles for computers in a local area network.
The first role is a being clients which use but do not provide network resources.
The second one is a being peers which both use and provide network resources. The last
one is a being servers which provide network resources. The role of a computer is
determined simply by use in the network many times.
Server (domain) / Client Networks
Server-based (also called client-server) networks are defined by the presence of
servers on a network that provide security and administration of the networks. It consists
with many clients and one or more servers. Clients (often called the "front end") request
services, such as file storage and printing, and servers (often called the "back end")
deliver them.
In Windows NT or Windows 2000, server-based networks are organized into
domains. Domains are collections of networks and clients that share security trust
information. Domain security and logon permission are controlled by special servers
called domain controllers. There is one master domain controller, called the Primary
Domain Controller (PDC) and the secondary domain controllers called Backup Domain
Controller (BDC) may assist PDC during busy times or when the PDC is not available for
some reason.

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

The
server-based
networks
have
many
advantages,
including:
Central file storage, which allows all users to work form the same set of data and
provides easy backup of critical data and keeps data from getting lost among computers
Ability of servers to pool available hardware and software, lowering overall costs
Optimized dedicated servers, which are faster than peers at sharing network
Freeing
of
users
from
the
task
of
managing
network
Easy
manageability
of
a
large
number
of
users
Ability
to
share
expensive
equipment,
such
as
laser
printers
Less intrusive strong central security, since a single password need to access all shared
resources on the network
Server-based
networks
also
have
some
disadvantages,
including:
Expensive
dedicated
hardware
Expensive network operating system software and client licenses
A dedicated network administrator (usually required)
Peer Networks :
Every computer on peer network is equal and can communicate with any other
computer on the network to which it has been granted access rights. So basically, every
computer on peer network functions as both a server and a client. The peer network
is more common in small business.
The advantages are:
No extra investment for server software and hardware are needed
No network administrator is needed
Easy setup
Lower cost
The disadvantages are:
Additional load on computers for resource sharing
Lack of central organization, which can make data hard to find
Users must administer their own computers
Weak and intrusive security
Hybrid Networks :
Hybrid networks have all three types of computers and have active domains and
workgroups. This means that network users have access to any resources being shared by
peers in their workgroup while most shared resources are located on servers
The advantages of hybrid networks are same as the advantages of server-based and peerbased networks. Hybrid network shares the disadvantages of server-based network.

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

Network Topology
Network topology are the physical layout of the network that the locations of the
computers and how the cable is run between them. It is important to use the right
topology. Each topology has its own strengths and weakness.
Bus topology
A bus topology connects computers along a single or more cable to connect
linearly as figure 1. A network that uses a bus topology is referred to as a "bus network"
which was the original form of Ethernet networks. Ethernet 10Base2 (also known as
thinnet) is used for bus topology.

Bus topology is the cheapest way of connecting computers to form a workgroup or


departmental LAN, but it has the disadvantage that a single loose connection or cable
break can bring down the entire LAN
Termination is important issue in bus networks. The electrical signal from a
transmitting computer is free to travel the entire length of the cable. Without the
termination, when the signal reaches the end of the wire, it bounces back and travels back
up the wire. When a signal echoes back and forth along an unterminated bus, it is called
ringing. The terminators absorb the electrical energy and stop the reflections.

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

Advantages of the bus are following.


Bus is easy to use and understand and inexpensive simple network
It is easy to extend a network by adding cable with a repeater that boosts the signal and
allows it to travel a longer distance.
Disadvantages are following.
A bus topology becomes slow by heavy network traffic with a lot of computer because
networks do not coordinate with each other to reserve times to transmit.
It is difficult to troubleshoot a bus because a cable break or loose connector will cause
reflections and bring down the whole network.
Star topology
A star topology links the computers by individual cables to a central unit, usually
a hub as in figure 2. When a computer or other networking component transmits a signal
to the network, the signal travels to the hub. Then, the hub forwards the signal
simultaneously to all other components connected to the hub. Ethernet 10BaseT is a
network based on the star topology. Star topology is the most popular way to connect
computers in a workgroup or departmental network.

Figure 2: Star topology

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

Advantages of star topology are such as:


The failure of a single computer or cable doesn't bring down the entire network.
The centralized networking equipment can reduce costs in the long run by making
network management much easier.
It allows several cable types in same network with a hub that can accommodate multiple
cable types.
Disadvantages of star topology are such as:
Failure of the central hub causes the whole network failure.
It is slightly more expensive than using bus topology.
Ring topology
A ring topology connects the computers along a single path whose ends are joined
to form a circle as figure 3. The circle might be logical only but the physical arrangement
of the cabling might be similar to star topology, with a hub or concentrator at the center.
The ring topology is commonly used in token ring networks that the ring of a token ring
network is concentrated inside a device called a Multistation Access Unit (MAU) and
fiber Distributed Data Interface (FDDI) networks that the ring in this case is both a
physical and logical ring and usually runs around a campus or collection of buildings to
form a high-speed backbone network.

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

Figure 3: Ring topology


Advantages are following:
One computer cannot monopolize the network.
It continue to function after capacity is exceeded but the speed will be slow.
Disadvantages are following:
Failure of one computer can affect the whole network.
It is difficult to troubleshoot.
Adding and removing computers disrupts the network.
Mesh topology
In a mesh topology, each computer on network has redundant data paths as
showing in figure 4. The mesh topology provides fault tolerance-if a wire, hub, switch, or
other component fails, data can travel along an alternate path. A diagram of a mesh
network looks like a fishing net. A mesh topology is most often used in large backbone
networks in which failure of a single switch or router can result in a large portion of the
network going down.

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

Figure 4: Mesh topology

Internet Protocol Suite


The Internet Protocol Suite (commonly known as TCP/IP) is the set of
communications protocols used for the Internet and other similar networks. It is named
from two of the most important protocols in it: the Transmission Control Protocol (TCP)
and the Internet Protocol (IP), which were the first two networking protocols defined in
this standard. Today's IP networking represents a synthesis of several developments that
began to evolve in the 1960s and 1970s, namely the Internet and LANs (Local Area
Networks), which emerged in the mid- to late-1980s, together with the advent of the
World Wide Web in the early 1990s.
The Internet Protocol Suite, like many protocol suites, may be viewed as a set of layers.
Each layer solves a set of problems involving the transmission of data, and provides a
well-defined service to the upper layer protocols based on using services from some
lower layers. Upper layers are logically closer to the user and deal with more abstract
data, relying on lower layer protocols to translate data into forms that can eventually be
physically transmitted.

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

The TCP/IP model consists of four layers (RFC 1122).[1][2] From lowest to highest, these
are the Link Layer, the Internet Layer, the Transport Layer, and the Application Layer.

History
The Internet Protocol Suite resulted from work done by Defense Advanced Research
Projects Agency (DARPA) in the early 1970s. After building the pioneering ARPANET
in 1969, DARPA started work on a number of other data transmission technologies. In
1972, Robert E. Kahn was hired at the DARPA Information Processing Technology
Office, where he worked on both satellite packet networks and ground-based radio packet
networks, and recognized the value of being able to communicate across them. In the
spring of 1973, Vinton Cerf, the developer of the existing ARPANET Network Control
Program (NCP) protocol, joined Kahn to work on open-architecture interconnection
models with the goal of designing the next protocol generation for the ARPANET.
By the summer of 1973, Kahn and Cerf had worked out a fundamental reformulation,
where the differences between network protocols were hidden by using a common
internetwork protocol, and, instead of the network being responsible for reliability, as in
the ARPANET, the hosts became responsible.
With the role of the network reduced to the bare minimum, it became possible to join
almost any networks together, no matter what their characteristics were, thereby solving
Kahn's initial problem. One popular saying has it that TCP/IP, the eventual product of
Cerf and Kahn's work, will run over "two tin cans and a string."
A computer called a router (a name changed from gateway to avoid confusion with other
types of gateways) is provided with an interface to each network, and forwards packets
back and forth between them. The idea was worked out in more detailed form by Cerf's
networking research group at Stanford in the 197374 period, resulting in the first TCP
specification
DARPA then contracted with BBN Technologies, Stanford University, and the University
College London to develop operational versions of the protocol on different hardware
platforms. Four versions were developed: TCP v1, TCP v2, a split into TCP v3 and IP v3
in the spring of 1978, and then stability with TCP/IP v4 the standard protocol still in
use on the Internet today.
In March 1982, the US Department of Defense declared TCP/IP as the standard for all
military computer networking In 1985, the Internet Architecture Board held a three day
workshop on TCP/IP for the computer industry, attended by 250 vendor representatives,
promoting the protocol and leading to its increasing commercial use.

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

Layers in the Internet Protocol Suite


The concept of layers
The TCP/IP suite uses encapsulation to provide abstraction of protocols and services.
Such encapsulation usually is aligned with the division of the protocol suite into layers of
general functionality. In general, an application (the highest level of the model) uses a set
of protocols to send its data down the layers, being further encapsulated at each level.
This may be illustrated by an example network scenario, in which two Internet host
computers communicate across local network boundaries constituted by their
internetworking gateways (routers).
The following figure shows the TCP/IP architecture and in which two Internet host
computers communicate across local network boundaries.
Application Layer
Transport Layer
Internet Layer
Link Layer

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

Encapsulation of application data descending


through the protocol stack.

TCP/IP stack operating on two hosts connected via two


routers and the corresponding layers used at each hop

The functional groups of protocols and methods are the Application Layer, the Transport
Layer, the Internet Layer, and the Link Layer (RFC 1122). It should be noted that this

10

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

model was not intended to be a rigid reference model into which new protocols have to fit
in order to be accepted as a standard.
The following table provides some examples of the protocols grouped in their respective
layers.
DNS, TFTP, TLS/SSL, FTP, Gopher, HTTP, IMAP, IRC,
NNTP, POP3, SIP, SMTP,SMPP, SNMP, SSH, Telnet, Echo,
RTP, PNRP, rlogin, ENRP
Application
Routing protocols like BGP and RIP which run over TCP/UDP,
may also be considered part of the Internet Layer.

Transport

TCP, UDP, DCCP, SCTP, IL, RUDP, RSVP

IP (IPv4, IPv6) ICMP, IGMP, and ICMPv6


Internet

Link

OSPF for IPv4 was initially considered IP layer protocol since it


runs per IP-subnet, but has been placed on the Link since RFC
2740.

ARP, RARP, OSPF (IPv4/IPv6), IS-IS, NDP

Different authors have interpreted the RFCs differently regarding the question whether
the Link Layer (and the TCP/IP model) covers Physical Layer issues, or if a hardware
layer is assumed below the Link Layer. Some authors have tried to use other names for
the Link Layer, such as network interface layer, in view to avoid confusion with the Data
Link Layer of the seven layer OSI model. Others have attempted to map the Internet
Protocol model onto the OSI Model. The mapping often results in a model with five
layers where the Link Layer is split into a Data Link Layer on top of a Physical Layer. In
literature with a bottom-up approach to Internet communication [8][9][11], in which hardware
issues are emphasized, those are often discussed in terms of Physical Layer and Data
Link Layer.
The Internet Layer is usually directly mapped into the OSI Model's Network Layer, a
more general concept of network functionality. The Transport Layer of the TCP/IP model,
sometimes also described as the host-to-host layer, is mapped to OSI Layer 4 (Transport
Layer), sometimes also including aspects of OSI Layer 5 (Session Layer)

11

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

functionality. OSI's Application Layer, Presentation Layer, and the remaining


functionality of the Session Layer are collapsed into TCP/IP's Application Layer. The
argument is that these OSI layers do usually not exist as separate processes and protocols
in Internet applications.
However, the Internet protocol stack has never been altered by the Internet Engineering
Task Force from the four layers defined in RFC 1122. The IETF makes no effort to
follow the OSI model although RFCs sometimes refer to it. The IETF has repeatedly
stated that Internet protocol and architecture development is not intended to be OSIcompliant.

The History of the Net


How the Internet came about
The foundations of the Internet were formed when packet-switching
networks came into operation in the 1960s. Transmitted data is
broken up into small packets of data, sent to its destination, and
reassembled at the other side. This means that a single signal can be
routed to multiple users, and an interrupted packet may be re-sent
without loss of transmission. Packets can be compressed for speed and
encrypted for security.
Computers at the time were massive, primitive structures. The only
type of network in operation before was made up of terminals that
logged into mainframes. This is similar to the present-day client/server
relationship we have with the modern Internet, except the computers
are usually comparable in terms of power, and so the Internet is known
as a peer-to-peer system.
ARPANET and onwards
Early packet-switching networks were set up in Europe. Development
of a similar system began in America in 1968, and went into operation
the year after in the US Defence Department's Advanced Research
Projects Agency (ARPA). The ARPANET used Network Control
Protocol as its transmission protocol from 1969 to 1982, when NCP was
replaced with the now-widespread TCP/IP.
Now that the technology was in place, strategies were put forth on
what to do with it. Eventually, the first large-scale Internet was created
a set of interconnected US military computers. The idea was simple:
if an attack was laid down on one part of the system, the rest of the
system would still be operational enough to blow the hell out of
whoever was attacking the country. Alternatively, losing the mainframe
12

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

in a centralized system would spell disaster. This was during the height
of the Cold War, and the inevitable nuclear war looked very close to
happening.

Services like Email found their first usage through the ARPANET
system, and its obvious benefits were lauded by all who participated.
The popular bulletin-board system, Usenet, was developed between
the 70s and 80s. Around this stage all of the main universities in the
US were connected to the network and used it for transmitting
experimental data and educational resources. It was found to be an
excellent method of sharing information. In 1973 the first international
(and indeed intercontinental) connection was made to the University
College of London in England.
The rise of USENET
USENET contributed more than anything else to the way the Internet
began to take off. The spirit of information sharing and discussion
that is the hallmark of the net was encapsulated in this system.
The introduction of personal computers in the late 70s brought a
large new audience to the developing Internet. They used email and
participated in discussions on networks like Usenet, Bitnet. The
Internet was growing exponentially. IRC (Internet Relay Chat) became
available in 1988 and communities formed in chat rooms.
World-Wide Web unleashed
It was only in 1991 that what we now call the World-Wide Web was
introduced, developed by Mr. Tim Berners-Lee, with assistance
from Robert Caillau (while both were working at CERN. Tim's now a
member of the W3C). Tim saw the need for a standard linked
information system accessible across the range of different
computers in use. It had to be simple so that it could work on both
dumb terminals and high-end graphical X-Window platforms. He got
some pages up and was able to access them with his 'browser'.
Quickly researchers got interested and started designing web sites and
browsers. In 1993 the first proper web-browser, Mosaic, took the
Internet by storm; having been developed at the National Center for
Supercomputer Applications (NCSA). As soon as it was ported to PCs
and Macs it immediately effected a boom in web usage.

13

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

Quickly services were set up for domain registration and sites began
turning up on the web, running on very basic HTML. Even at this stage,
malicious viruses and worms were infiltrating computers connected to
the Internet. Important sites like the White House and Pizza Hut
appeared. Online shopping sites showed up.The www was quickly the
most popular service on the Internet.
It was around 1995 when the first large ISPs like AOL and CompuServe
began offering Internet access to the masses. Technology like Sun's
Java and search engines are released. The somewhat legendary
browser war was in full swing between Netscape and Microsoft, with
new browser releases coming every month and the web becoming

increasingly fragmented. Despite this, the public's enthusiasm for the


Internet went unbridled.
Today, in whatever year this is, the web is still growing at an amazing
rate. Technology has improved considerably, and the web is regarded
as an indispensable tool for education, business and entertainment.
There are billions of pages on the web, with thousands more being
added every hour. The Internet is a system that is nigh-on impossible
to destroy, and looks set to become an ever-larger influence on the
world in the future.

What is the Internet?


The Internet today is a large-scale network of millions of computers
that allows continuous communication across the globe. The various
applications of the Internet are:

The World-Wide Web (the web or WWW)


Electronic Mail (E-Mail)
File Transfer Protocol (FTP)
Internet Relay chat (IRC)
USENET (a news service)

14

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

The World-Wide Web


The www is the reason the Internet has become as popular as it has.
This is the part of the Internet that the majority of users see the
websites and the pages that make them up. The web is the most
widely used service of the Internet, accessed through a web browser
like Internet Explorer or Netscape Navigator. These pieces of software
are gradually integrating other parts of the Internet into them (most
notably email and ftp), so that eventually we will have one interface to
the entire array of services the Internet offers.
The web is an immense collection of web pages, linked together with
hypertext links. Thousands of new pages of information are added to
the heaving web every hour. Each page is placed on a server, a
computer continually connected to the rest of the web. The information
is then available to anyone else with access to the Internet. Web pages
can have a mixture of text, graphics and multimedia. Nowadays,
there's information on practically anything you could be interested in
available somewhere on the web.
The rapid growth of the internet was due to networking giants like
British Telecom, Hyundai, AT&T and others setting up fast and reliable
networks. Their role was to setup and maintain, monitor and expand
the existing networks. Hence another layer was formed above this
layer called ISPs. The networking giants gave access to the
internet via Gateways. Using ISP gateways it is perfectly possible to

15

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

route business or commerce data from one point of the globe to


another by using a heterogeneous mix of networks.
ISPs in turn offer clients access to the internet via their gateways as
paid for service. An ISPs gateway generally consists of a server with
permanent connection to the internet.
The servers connection to the internet is called its internet Pipeline.

ISPs

Client
A

HYUNDAI

Client
B

AT & T

Client
B

Branch A

Branch B

ISPs
DIRECT
ACCESS BY
MNCS
Client
A

BRITISH
TELECOME

The internet consists of two types of computers Servers and Clients:

16

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

i)
ii)

Computers which offer information to be read are called


Servers
Computers that read the information offered are called Clients

Servers run special software (Web sever software ) that allows them to
i)
ii)

Respond to client request for information


Accept data form clients

Some of the most popular server softwares are


Internet Information Server(IIS), Apache web server, Microsoft Personal
web server.
Clients run on special software called WEB browser: IE, Netscape etc
COMMUNICATING ON THE INTERNET
TCP/IP is the only protocol used to send data all around the internet.
In this (TCP) a set of communication protocols and (IP) a unique
address. Every machine connected to the internet must have an
address by which it can be located on the internet. This is called the IP
address of the machine. For the internet to function smoothly, no two
machines can have the same IP address. Hence each machine
connected to the internet must have a unique IP address, which
identifies that machine.
As the internet grew over the years it become increasingly
important to have a governing body, which allocated unique IP
addresses to organizations linked to the internet. An international body
called InterNIC, located in the USA, is responsible for registering
and assigning unique IP address to organizations wishing to
manage networks, which will be part of the Internet. A unique IP
address therefore points to an actual computer connected via
gateway to the internet. This computer is known as a Domain i.e a
place where information is available. This is Physical Domain on the
internet.
Conceptually, a server, which has a permanent IP address(i.e. a
Physical Domain )
Can provide

17

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

A gateway to other computers to access the Internet And/Or


Provide information for Internet clients to read And/Or

Provide a physical location on which several virtual domains can


be hosted

When a Web site provides Internet clients information to read,


the site is mounted as a Virtual Domain on an internet server, which
is its (host) Physical Domain.
Virtual
Domains
are
identified
by
a
name(e.g.www.rgcetpdy.ac.in). Just like a Physical Domain needs to
have a unique IP address, so also virtual domain Names need to be
unique in the internet. Al virtual Domain Names must be registered with
InterNIC. one internet server may host several Virtual domains.

Virtual Domains are can be conceptualized as sub directories


on the internet servers hard disk drive. The information that internet
clients wish to read whould be files within the sub directory.
When an internet client connected to an internet server some
s/w running on the internet sever must respond to the internet clients
request for information. The software that runs on the internet server
and respond to the internet client request for information is called web
server s/w.
Traditionally, this sub directory on the internet server is
wwwroot and the file is automatically picked up and passed to the4
Internet client.

18

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

Multiple Virtual Domains Hosted On A Single Physical Domain


A single computer having a permanent IP address and connected
to the Internet can host Multiple virtual domains on its hard disk
drive. There are several Internet servers(i.e. Physical domains) which
do nothing but host with multiple Virtual Domains.
Companies who wish to have an internet presence without
registering a physical domain with InterNIC and then creating a virtual
domain on the physical domain simply rent hard disk space on these
host Servers.
Internet Clients will now not only need to connect to the correct
physical domain but also to the correct virtual domain hosted on the
physical domain.
Conceptually, a sub directory is created on the Internet host
server. The company , which has purchased hard disk space on the
internet host server, create its web site with in this sub directory. This
sub directory will hold the default startup file(e.g Index.html)

which the web server send back to the client when the client connects
to the physical domain and points to a specific virtual domain hosted
on physical domain.
When an internet client requests for a connection to a virtual
domain on the internet, the request is routed to the proper internet
server using TCP/IP. The web server running on this internet Server
then handles the request, resolves(maps) the virtual domain Name
sent along with the request to an appropriate sub directory on the
internet server where the web site is hosted.
19

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

Internet server Identities (How to get Physical Domain)


InterNIC, a quasi government body in the USA registers and issues
Internet Servers their unique IP addresses.
InterNIC also authorizes organizations in other countries to issues
IP addresses. In India NCST (National Center Of Software Technology) a
quasi government body authorized to issue permanent IP addresses.

Applications of Internet
E-Mail
Electronic Mail works in much the same way as traditional mail (now
charmingly labelled 'snail-mail') does. Anyone is allowed to sign up for
an email address and then people can send you messages, or attach
files from their computer and send them too. The main benefit of email
is the close to instantaneous delivery of messages that occurs. You
can send an email to the other side of the world and it will arrive in less
than a minute. You can also sign up to weekly newsletters and have
information you want delivered right to your computer.
File Transfer Protocol
While web pages are transferred between computers using the http
protocol, other types of files are sent using FTP. People can share files,
like music and videos, among each other and the rest of the world by
uploading them to a server and allowing others to download them to
their own computers.
Internet Relay Chat
IRC is a service that allows you to connect to your chosen channel and
talk in real-time to people with the same interests as you. You can
download mIRC and start chatting right away.
USENET
USENET (Unix User Network) is a system of bulletin boards where you
and anyone else can post messages and people will read and reply to
them. As with IRC, you will find boards set up for all sorts of groups of
people.

IP address
20

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

An Internet Protocol (IP) address is a numerical identification and logical address that is
assigned to devices participating in a computer network utilizing the Internet Protocol for
communication between its nodes.Although IP addresses are stored as binary numbers,
they are usually displayed in human-readable notations, such as 208.77.188.166 (for
IPv4), and 2001:db8:0:1234:0:567:1:1 (for IPv6). The role of the IP address has been
characterized as follows: "A name indicates what we seek. An address indicates where it
is. A route indicates how to get there."
The original designers of TCP/IP defined an IP address as a 32-bit number and this
system, now named Internet Protocol Version 4 (IPv4), is still in use today. However, due
to the enormous growth of the Internet and the resulting depletion of the address space, a
new addressing system (IPv6), using 128 bits for the address.
The Internet Protocol also has the task of routing data packets between networks, and IP
addresses specify the locations of the source and destination nodes in the topology of the
routing system. For this purpose, some of the bits in an IP address are used to designate a
subnetwork. The number of these bits is indicated in CIDR notation, appended to the IP
address, e.g., 208.77.188.166/24.
With the development of private networks and the threat of IPv4 address exhaustion, a
group of private address spaces was set aside by RFC 1918. These private addresses may
be used by anyone on private networks. They are often used with network address
translators to connect to the global public Internet.
The Internet Assigned Numbers Authority (IANA) manages the IP address space
allocations globally. IANA works in cooperation with five Regional Internet Registries
(RIRs) to allocate IP address blocks to Local Internet Registries (Internet service
providers) and other entities

IP versions
The Internet Protocol (IP) has two versions currently in use Each version has its own
definition of an IP address. Because of its prevalence, the generic term IP address

21

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

typically

still

refers

to

the

addresses

defined

by

IPv4.

An illustration of an IP address (version 4), in both dot-decimal notation and binary.

IP version 4 addresses
IPv4 uses 32-bit (4-byte) addresses, which limits the address space to 4,294,967,296 (232)
possible unique addresses. However, IPv4 reserves some addresses for special purposes
such as private networks (~18 million addresses) or multicast addresses (~270 million
addresses). This reduces the number of addresses that can be allocated as public Internet
addresses, and as the number of addresses available is consumed, an IPv4 address
shortage appears to be inevitable in the long run. This limitation has helped stimulate the
push towards IPv6, which is currently in the early stages of deployment and is currently
the only offering to replace IPv4.
IPv4 addresses are usually represented in dot-decimal notation (four numbers, each
ranging from 0 to 255, separated by dots, e.g. 208.77.188.166). Each part represents 8
bits of the address, and is therefore called an octet. In less common cases of technical
writing, IPv4 addresses may be presented in hexadecimal, octal, or binary
representations. When converting, each octet is usually treated as a separate number.

IPv4 networks
In the early stages of development of the Internet protocol, network administrators
interpreted an IP address as a structure of network number and host number. The highest
order octet (most significant eight bits) was designated the network number and the rest
of the bits were called the rest field or host identifier and were used for host numbering
within a network. This method soon proved inadequate as additional networks developed
that were independent from the existing networks already designated by a network
number. In 1981, the Internet addressing specification was revised with the introduction
of classful network architecture.

Classful network design allowed for a larger number of individual network assignments.
The first three bits of the most significant octet of an IP address was defined as the class
of the address. Three classes (A, B, and C) were defined for universal unicast addressing.

22

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

Depending on the class derived, the network identification was based on octet boundary
segments of the entire address. Each class used successively additional octets in the
network identifier, thus reducing the possible number of hosts in the higher order classes
(B and C). The following table gives an overview of this system.

Class

First octet in
binary

Range of Network Host Possible number


Possible
first octet
ID
ID
of networks number of hosts
224 - 2 =
16,777,214

0XXXXXXX

0 - 127

b.c.d 27 = 128

10XXXXXX

128 - 191

a.b

c.d

214 = 16,384

216 - 2 = 65,534

110XXXXX

192 - 223

a.b.c

221 = 2,097,152

28 - 2 = 254

The articles 'subnetwork' and 'classful network' explain the details of this design.
Although classful network design was a successful developmental stage, it proved
unscalable in the rapid expansion of the Internet and was abandoned when Classless
Inter-Domain Routing (CIDR) was created for the allocation of IP address blocks and
new rules of routing protocol packets using IPv4 addresses. CIDR is based on variablelength subnet masking (VLSM) to allow allocation and routing on arbitrary-length
prefixes.
Today, remnants of classful network concepts function only in a limited scope as the
default configuration parameters of some network software and hardware components
(e.g. netmask), and in the technical jargon used in network administrators' discussions.

IP version 6 addresses

23

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

An illustration of an IP address (version 6), in hexadecimal and binary.


The rapid exhaustion of IPv4 address space, despite conservation techniques, prompted
the Internet Engineering Task Force (IETF) to explore new technologies to expand the
Internet's addressing capability. The permanent solution was deemed to be a redesign of
the Internet Protocol itself. This next generation of the Internet Protocol, aimed to replace
IPv4 on the Internet, was eventually named Internet Protocol Version 6 (IPv6). The
address size was increased from 32 to 128 bits or 16 octets, which, even with a generous
assignment of network blocks, is deemed sufficient for the foreseeable future.
Mathematically, the new address space provides the potential for a maximum of 2 128, or
about 3.403 1038 unique addresses.
The new design is not based on the goal to provide a sufficient quantity of addresses
alone, but rather to allow efficient aggregation of subnet routing prefixes to occur at
routing nodes. As a result, routing table sizes are smaller, and the smallest possible
individual allocation is a subnet for 264 hosts, which is the size of the square of the size of
the entire IPv4 Internet. At these levels, actual address utilization rates will be small on
any IPv6 network segment. The new design also provides the opportunity to separate the
addressing infrastructure of a network segment--that is the local administration of the
segment's available space--from the addressing prefix used to route external traffic for a
network. IPv6 has facilities that automatically change the routing prefix of entire
networks should the global connectivity or the routing policy change without requiring
internal redesign or renumbering.
The large number of IPv6 addresses allows large blocks to be assigned for specific
purposes and, where appropriate, to be aggregated for efficient routing. With a large
address space, there is not the need to have complex address conservation methods as
used in classless inter-domain routing (CIDR).
All modern desktop and enterprise server operating systems include native support for the
IPv6 protocol, but it is not yet widely deployed in other devices, such as home
networking routers, voice over Internet Protocol (VoIP) and multimedia equipment, and
network peripherals.

Example of an IPv6 address:

24

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY


2001:0db8:85a3:08d3:1319:8a2e:0370:7334

IP address translation
Multiple client devices can appear to share IP addresses: either because they are part of a
shared hosting web server environment or because an IPv4 network address translator
(NAT) or proxy server acts as an intermediary agent on behalf of its customers, in which
case the real originating IP addresses might be hidden from the server receiving a request.
A common practice is to have a NAT hide a large number of IP addresses in a private
network. Only the "outside" interface(s) of the NAT need to have Internet-routable
addresses.
Most commonly, the NAT device maps TCP or UDP port numbers on the outside to
individual private addresses on the inside. Just as a telephone number may have sitespecific extensions, the port numbers are site-specific extensions to an IP address.
In small home networks, NAT functions usually take place in a residential gateway
device, typically one marketed as a "router". In this scenario, the computers connected to
the router would have 'private' IP addresses and the router would have a 'public' address
to communicate with the Internet. This type of router allows several computers to share
one public IP address.

Sockets and Ports


TCP multiplexes multiple connections to a single Internet host using sockets and ports.
A socket is a network communications endpoint. The analogy is to a wire (the network
data connection) being plugged into a socket.
Sockets come in two primary flavors. An active socket is connected to a remote active
socket via an open data connection. Closing the connection destroys the active sockets at
each endpoint. A passive socket is not connected, but rather awaits an incoming
connection, which will spawn a new active socket.

25

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

A socket is not a port, though there is a close relationship between them. A socket is
associated with a port, though this is a many-to-one relationship. Each port can have a
single passive socket, awaiting incoming connections, and multiple active sockets, each
corresponding to an open connection on the port.

Domain Name System


The Internet Protocol Suite
Application Layer
BGP DHCP DNS FTP GTP HTTP IMAP
IRC Megaco MGCP NNTP NTP POP

26

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

RIP RPC RTP RTSP SDP SIP SMTP


SNMP SOAP SSH Telnet TLS/SSL XMPP
(more)
Transport Layer
TCP UDP DCCP SCTP RSVP ECN
(more)
Internet Layer
IP (IPv4, IPv6) ICMP ICMPv6 IGMP IPsec
(more)
Link Layer
ARP RARP NDP OSPF Tunnels (L2TP)
PPP Media Access Control (Ethernet, MPLS,
DSL, ISDN, FDDI) Device Drivers (more)
This box: view talk edit

The Domain Name System (DNS) is a hierarchical naming system for computers,
services, or any resource participating in the Internet. It associates various information
with the domain names assigned to each of the participants. Most importantly, it
translates domain names meaningful to humans into the numerical (binary) identifiers
associated with networking equipment for the purpose of locating and addressing these
devices world-wide. An often used analogy to explain the Domain Name System is that it
serves as the "phone book" for the Internet by translating human-friendly computer
hostnames into IP addresses. For example, www.example.com translates to
208.77.188.166.
The Domain Name System makes it possible to assign domain names to groups of
Internet users in a meaningful way, independent of each user's physical location. Because
of this, World-Wide Web (WWW) hyperlinks and Internet contact information can
remain consistent and constant even if the current Internet routing arrangements change
or the participant uses a mobile device. Internet domain names are easier to remember
than
IP
addresses
such
as
208.77.188.166
(IPv4)
or
2001:db8:1f70::999:de8:7648:6e8 (IPv6). People take advantage of this when they
recite meaningful URLs and e-mail addresses without having to know how the machine
will actually locate them.

27

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

The Domain Name System distributes the responsibility of assigning domain names and
mapping those names to IP addresses by designating authoritative name servers for each
domain. Authoritative name servers are assigned to be responsible for their particular
domains, and in turn can assign other authoritative name servers for their sub-domains.
This mechanism has made the DNS distributed, fault tolerant, and helped avoid the need
for a single central register to be continually consulted and updated.
In general, the Domain Name System also stores other types of information, such as the
list of mail servers that accept email for a given Internet domain. By providing a worldwide, distributed keyword-based redirection service, the Domain Name System is an
essential component of the functionality of the Internet.
Other identifiers such as RFID tags, UPC codes, International characters in email
addresses and host names, and a variety of other identifiers could all potentially utilize
DNS.
The Domain Name System also defines the technical underpinnings of the functionality
of this database service. For this purpose it defines the DNS protocol, a detailed
specification of the data structures and communication exchanges used in DNS, as part of
the Internet Protocol Suite (TCP/IP). The DNS protocol was developed and defined in the
early 1980s and published by the Internet Engineering Task Force (cf. History).

The domain name space

28

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

Domain names, arranged in a tree, cut into zones, each served by a nameserver.
The domain name space consists of a tree of domain names. Each node or leaf in the tree
has zero or more resource records, which hold information associated with the domain
name. The tree sub-divides into zones beginning at the root zone. A DNS zone consists of
a collection of connected nodes authoritatively served by an authoritative nameserver.
(Note that a single nameserver can host several zones.)
Administrative responsibility over any zone may be divided, thereby creating additional
zones. Authority is said to be delegated for a portion of the old space, usually in form of
sub-domains, to another nameserver and administrative entity. The old zone ceases to be
authoritative for the new zone.

Parts of a domain name


A domain name usually consists of two or more parts (technically labels), which are
conventionally written separated by dots, such as example.com.

The rightmost label conveys the top-level domain (for example, the address
www.example.com has the top-level domain com).
Each label to the left specifies a subdivision, or subdomain of the domain above
it. Note: subdomain expresses relative dependence, not absolute dependence.
For example: example.com is a subdomain of the com domain, and
www.example.com is a subdomain of the domain example.com. In theory, this
subdivision can go down 127 levels. Each label can contain up to 63 octets. The

whole domain name may not exceed a total length of 253 octets. [6] In practice, some
domain registries may have shorter limits.
29

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

A hostname refers to a domain name that has one or more associated IP addresses;
ie: the 'www.example.com' and 'example.com' domains are both hostnames,
however, the 'com' domain is not.

DNS servers
The Domain Name System is maintained by a distributed database system, which uses
the client-server model. The nodes of this database are the name servers. Each domain or
subdomain has one or more authoritative DNS servers that publish information about that
domain and the name servers of any domains subordinate to it. The top of the hierarchy is
served by the root nameservers: the servers to query when looking up (resolving) a toplevel domain name (TLD).

DNS resolvers
The client-side of the DNS is called a DNS resolver. It is responsible for initiating and
sequencing the queries that ultimately lead to a full resolution (translation) of the
resource sought, e.g., translation of a domain name into an IP address.
A DNS query may be either a recursive query or a non-recursive query:

A non-recursive query is one in which the DNS server may provide a partial
answer to the query (or give an error).
A recursive query is one where the DNS server will fully answer the query (or
give an error). DNS servers are not required to support recursive queries.

The resolver (or another DNS server acting recursively on behalf of the resolver)
negotiates use of recursive service using bits in the query headers.
Resolving usually entails iterating through several name servers to find the needed
information. However, some resolvers function simplistically and can communicate only
with a single name server. These simple resolvers rely on a recursive query to a recursive
name server to perform the work of finding information for them.

Address resolution mechanism


(This description deliberately uses the fictional .example TLD in accordance with
the DNS guidelines.)
In theory a full host name may have several name segments, (e.g
ahost.ofasubnet.ofabiggernet.inadomain.example). In practice, full host names will
frequently consist of just three segments (ahost.inadomain.example, and most often

www.inadomain.example). For querying purposes, software interprets the name segment


by segment, from right to left. At each step along the way, the program queries a
corresponding DNS server to provide a pointer to the next server which it should consult.
30

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

A DNS recursor consults three nameservers to resolve the address www.wikipedia.org.


As originally envisaged, the process was as simple as:
1. the local system is pre-configured with the known addresses of the root servers in
a file of root hints, which need to be updated periodically by the local
administrator from a reliable source to be kept up to date with the changes which
occur over time.
2. query one of the root servers to find the server authoritative for the next level
down (so in the case of our simple hostname, a root server would be asked for the
address of a server with detailed knowledge of the example top level domain).
3. querying this second server for the address of a DNS server with detailed
knowledge of the second-level domain (inadomain.example in our example).
4. repeating the previous step to progress down the name, until the final step which
would, rather than generating the address of the next DNS server, return the final
address sought.
The diagram illustrates this process for the real host www.wikipedia.org.
The mechanism in this simple form has a difficulty: it places a huge operating burden on
the root servers, with every search for an address starting by querying one of them. Being
as critical as they are to the overall function of the system, such heavy use would create
an insurmountable bottleneck for trillions of queries placed every day. In practice caching
is used to overcome this problem, and in actual fact root nameservers deal with very little
of the total traffic.

Tunneling protocol
Computer networks use a tunneling protocol when one network protocol (the delivery
protocol) encapsulates a different payload protocol. By using tunneling one can (for
example) carry a payload over an incompatible delivery-network, or provide a secure
path through an untrusted network.

Tunneling typically contrasts with a layered protocol model such as those of OSI or
TCP/IP. The tunnel protocol usually (but not always) operates at a higher level in the
model than does the payload protocol, or at the same level. Protocol encapsulation carried

31

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

out by conventional layered protocols, in accordance with the OSI model or TCP/IP
model (for example: HTTP over TCP over IP over PPP over a V.92 modem) does not
count as tunneling.
To understand a particular protocol stack, network engineers must understand both the
payload and delivery protocol sets.
As an example of network layer over network layer, Generic Routing Encapsulation
(GRE), a protocol running over IP (IP Protocol Number 47), often serves to carry IP
packets, with RFC 1918 private addresses, over the Internet using delivery packets with
public IP addresses. In this case, the delivery and payload protocols are compatible, but
the payload addresses are incompatible with those of the delivery network.
In contrast, an IP payload might believe it sees a data link layer delivery when it is
carried inside the Layer 2 Tunneling Protocol (L2TP), which appears to the payload
mechanism as a protocol of the data link layer. L2TP, however, actually runs over the
transport layer using User Datagram Protocol (UDP) over IP. The IP in the delivery
protocol could run over any data-link protocol from IEEE 802.2 over IEEE 802.3 (i.e.,
standards-based Ethernet) to the Point-to-Point Protocol (PPP) over a dialup modem link.
Tunneling protocols may use data encryption to transport insecure payload protocols over
a public network (such as the Internet), thereby providing VPN functionality. IPSec has
an end-to-end Transport Mode, but can also operate in a tunneling mode through a trusted
security gateway.

Generic Routing Encapsulation


Generic Routing Encapsulation (GRE) is a tunneling protocol developed by Cisco that
can encapsulate a wide variety of network layer protocol packet types inside IP tunnels,
creating a virtual point-to-point link to Cisco routers at remote points over an IP
internetwork.

Overview
GRE tunnels are designed to be completely stateless. This means that each tunnel endpoint does not keep any information about the state or availability of the remote tunnel
end-point. A consequence of this is that the local tunnel end-point router does not have
the ability to bring the line protocol of the GRE tunnel interface down if the remote endpoint is unreachable. The ability to mark an interface as down when the remote end of the
link is not available is used in order to remove any routes (specifically static routes) in the
routing table that use that interface as the outbound interface. Specifically, if the line
protocol for an interface is changed to down, then any static routes that point out that

32

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

interface are removed from the routing table. This allows for the installation of an
alternate (floating) static route or for policy-based routing (PBR) to select an alternate
next-hop or interface.
Normally, a GRE tunnel interface comes up as soon as it is configured and it stays up as
long as there is a valid tunnel source address or interface which is up. The tunnel
destination IP address must also be routable. This is true even if the other side of the
tunnel has not been configured. This means that a static route or PBR forwarding of
packets via the GRE tunnel interface remains in effect even though the GRE tunnel
packets do not reach the other end of the tunnel.

Tunnel keepalives
The GRE tunnel keepalive mechanism is slightly different than for Ethernet or serial
interfaces. It gives the ability for one side to originate and receive keepalive packets to
and from a remote router even if the remote router does not support GRE keepalives.
Since GRE is a packet tunneling mechanism for tunneling IP inside IP, a GRE IP tunnel
packet can be built inside another GRE IP tunnel packet. For GRE keepalives, the sender
pre-builds the keepalive response packet inside the original keepalive request packet so
that the remote end only needs to do standard GRE decapsulation of the outer GRE IP
header and then forward the inner IP GRE packet. This mechanism causes the keepalive
response to forward out the physical interface rather than the tunnel interface. This means
that the GRE keepalive response packet is not affected by any output features on the
tunnel interface.
Another attribute of GRE tunnel keepalives is that the keepalive timers on each side are
independent and do not have to match. The problem with the configuration of keepalives
only on one side of the tunnel is that only the router that has keepalives configured marks
its tunnel interface as down if the keepalive timer expires. The GRE tunnel interface on
the other side, where keepalives are not configured, remains up even if the other side of
the tunnel is down. The tunnel can become a black-hole for packets directed into the
tunnel from the side that did not have keepalives configured. In a large hub-and-spoke
GRE tunnel network, it might be appropriate to only configure GRE keepalives on the
spoke side and not on the hub side. This is because it is often more important for the
spoke to discover that the hub is unreachable and therefore switch to a backup path (Dial
Backup for example).
Before GRE keepalives were implemented, there were only three reasons for a GRE
tunnel to shut down:

There is no route to the tunnel destination address.


The interface that anchors the tunnel source is down.
The route to the tunnel destination address is through the tunnel itself.

These three rules (missing route, interface down and mis-routed tunnel destination) are
problems local to the router at the tunnel endpoints and do not cover problems in the

33

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

intervening network. For example, these rules do not cover the case in which the GRE
tunneled packets are successfully forwarded, but are lost before they reach the other end
of the tunnel. This causes data packets that go through the GRE tunnel to be "black
holed", even though an alternate route that uses PBR or a floating static route via another
interface is potentially available. Keepalives on the GRE tunnel interface are used in
order to solve this issue in the same way as keepalives are used on physical interfaces.
With Cisco IOS Software Release 12.2(8)T, it is possible to configure keepalives on a
point-to-point GRE tunnel interface. With this change, the tunnel interface dynamically
shuts down if the keepalives fail for a certain period of time. In order to better understand
how GRE tunnel keepalives work, these sections discuss some other common keepalive
mechanisms.

Example uses

In conjunction with PPTP to create VPNs.


In conjunction with IPsec VPNs to allow passing of routing information between
connected networks.
In Mobility protocols.
In A8/A10 interfaces to encapsulate IP data to/from Packet Control Function
(PCF).
Linux and BSD can establish ad-hoc IP over GRE tunnels which are interoperable
with Cisco equipment.

Example protocol stack


OSI model layer

Protocol

5. Application

RADIUS

4. Transport

UDP

3. Network (GRE-encapsulated) IPv6

Encapsulation

GRE

3. Network

IPv4

2. Data Link

Ethernet

34

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

1. Physical

Ethernet physical layer

From what can be seen in the diagram above, protocol encapsulation (not specifically
GRE) breaks the layering order in the OSI model terms. It may be viewed as a separator
between two different protocol stacks, one acting as a carrier for another.

IP as a delivery protocol
GRE packets which are encapsulated within IP will use IP protocol type 47.

Packet header
A GRE packet header structure is represented in the diagram below.
Bits 04

57

C R K S s Recur

812

1315

1631

Flags

Version

Protocol Type

Checksum (optional)

Offset (optional)

Key (optional)

Sequence Number (optional)

Routing (optional)
The packet fields are as follows:
Checksum Present (C), 1-bit
The Checksum field is present and contains valid information if set. If either the
Checksum Present bit or the Routing Present bit are set, the Checksum and Offset
fields are both present.
Routing Present (R), 1-bit
If set then the Offset field is present and contains valid information. If either the
Checksum Present bit or the Routing Present bit are set, the Checksum and Offset
fields are both present.
35

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

Key Present (K), 1-bit


If set then the Key field is present and contains valid information.
Sequence Number present (capital S), 1-bit
If set then the Sequence Number field is present and contains valid information.
Strict Source Route (s), 1-bit
The meaning of this bit is defined in other documents. It is recommended that this
bit only be set if all of the Routing Information consists of Strict Source Routes.
Recursion Control (Recur), 3 bits
Contains the number of additional encapsulations which are permitted. 0 is the
default.
Flags, 5 bits
These bits are reserved and must be transmitted as 0.
Version, 3 bits
GRE protocol version. Normally must be cleared to 0 but in the case of PPTP it is
set to 1.
Protocol, 16 bits
Contains the protocol type of the payload packet. In general, the value will be the
Ethernet protocol type field for the packet. Additional values may be defined in
other documents.
Checksum, 16 bits
Contains the IP (one's complement) checksum of the GRE header and the payload
packet.
Offset, 16 bits
Indicates the byte offset from the start of the Routing field to the first byte of the
active Source Route Entry to be examined.
Key, 32 bits
Contains a number which was inserted by the encapsulator. The Key field is
intended to be used for identifying an individual traffic flow within a tunnel. Note
that Key field is not involved in any sort of security (despite its name.)
Sequence Number, 32 bits
Contains a number which is inserted by the encapsulator. It may be used by the
receiver to establish the order in which packets have been transmitted from the
encapsulator to the receiver.
Routing, variable length
This field is a list of SREs.

SSH tunneling
An SSH tunnel consists of an encrypted tunnel created through an SSH protocol
connection. Users may set up SSH tunnels to tunnel unencrypted traffic over a network
through an encrypted channel. For example, Windows machines can share files using the
SMB protocol, a non-encrypted protocol. If one were to mount a Microsoft Windows filesystem remotely through the Internet, someone snooping on the connection could see
transferred files. To mount the Windows file-system securely, one can establish an SSH

36

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

tunnel that routes all SMB traffic to the remote fileserver through an encrypted channel.
Even though the SMB protocol itself contains no encryption, the encrypted SSH channel
through which it travels offers security.
To set up an SSH tunnel, one configures an SSH client to forward a specified local port to
a port on the remote machine. Once the SSH tunnel has been established, the user can
connect to the specified local port to access the network service. The local port need not
have the same port number as the remote port.
SSH tunnels provide a means to bypass firewalls that prohibit certain Internet services
so long as a site allows outgoing connections. For example, an organization may prohibit
a user from accessing Internet web pages (port 80) directly without passing through the
organization's proxy filter (which provides the organization with a means of monitoring
and controlling what the user sees through the web). But users may not wish to have their
web traffic monitored or blocked by the organization's proxy filter. If users can connect to
an external SSH server, they can create an SSH tunnel to forward a given port on their
local machine to port 80 on a remote web server. To access the remote web server users
would point their browser to http://localhost/.
Some SSH clients support dynamic port forwarding that allows the user to create a
SOCKS 4/5 proxy. In this case users can configure their applications to use their local
SOCKS proxy server. This gives more flexibility than creating an SSH tunnel to a single
port as previously described. SOCKS can free the user from the limitations of connecting
only to a predefined remote port and server.

Tunneling to circumvent firewall policy


Users can also use tunneling to "sneak through" a firewall, using a protocol that the
firewall would normally block, but "wrapped" inside a protocol that the firewall does not
block, such as HTTP. If the firewall policy does not specifically exclude this kind of
"wrapping", this trick can function to get around the intended firewall policy.
Another HTTP-based tunneling method uses the HTTP CONNECT method/command. A
client issues the HTTP CONNECT command to an HTTP proxy. The proxy then makes a
TCP connection to a particular server:port, and relays data between that server:port and
the client connection. Because this creates a security hole, CONNECT-capable HTTP
proxies commonly restrict access to the CONNECT method. The proxy allows access
only to TLS/SSL-based HTTPS services.

37

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

Proxy server

Schematic representation of a proxy server, where the computer in the middle acts as the
proxy server between the other two.
In computer networks, a proxy server is a server (a computer system or an
application program) that acts as a go-between for requests from clients seeking resources
from other servers. A client connects to the proxy server, requesting some service, such as
a file, connection, web page, or other resource, available from a different server. The
proxy server evaluates the request according to its filtering rules. For example, it may
filter traffic by IP address or protocol. If the request is validated by the filter, the proxy
provides the resource by connecting to the relevant server and requesting the service on
behalf of the client. A proxy server may optionally alter the client's request or the server's
response, and sometimes it may serve the request without contacting the specified server.
In this case, it 'caches' responses from the remote server, and returns subsequent requests
for the same content directly.
A proxy server has two purposes:

To keep machines behind it anonymous (mainly for security)]


To speed up access to a resource (via caching). It is commonly used to cache web
pages from a web server.

A proxy server that passes requests and replies unmodified is usually called a
gateway or sometimes tunneling proxy.
A proxy server can be placed in the user's local computer or at various points
between the user and the destination servers or the Internet. A reverse proxy is a proxy
used as a front-end to accelerate and cache in-demand resources (such as a web page).

Types and functions


Proxy servers implement one or more of the following functions:

38

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

Caching proxy server


A caching proxy server accelerates service requests by retrieving content saved
from a previous request made by the same client or even other clients. Caching proxies
keep local copies of frequently requested resources, allowing large organizations to
significantly reduce their upstream bandwidth usage and cost, while significantly
increasing performance. Most ISPs and large businesses have a caching proxy. These
machines are built to deliver superb file system performance (often with RAID and
journaling) and also contain hot-rodded versions of TCP. Caching proxies were the first
kind of proxy server.
Some poorly-implemented caching proxies have had downsides (e.g., an inability to use
user authentication).
Another important use of the proxy server is to reduce the hardware cost. An
organization may have many systems on the same network or under control of a single
server, prohibiting the possibility of an individual connection to the Internet for each
system. In such a case, the individual systems can be connected to one proxy server, and
the proxy server connected to the main server.

Web proxy
A proxy that focuses on WWW traffic is called a "web proxy". The most common
use of a web proxy is to serve as a web cache. Most proxy programs (e.g. Squid) provide
a means to deny access to certain URLs in a blacklist, thus providing content filtering.
This is often used in a corporate, educational or library environment, and anywhere else
where content filtering is desired. Some web proxies reformat web pages for a specific
purpose or audience (e.g., cell phones and PDAs).
AOL dialup customers used to have their requests routed through an extensible
proxy that 'thinned' or reduced the detail in JPEG pictures. This sped up performance but
caused problems, either when more resolution was needed or when the thinning program
produced incorrect results. This is why in the early days of the web many web pages
would contain a link saying "AOL Users Click Here" to bypass the web proxy and to
avoid the bugs in the thinning software.

Content-filtering web proxy


A content-filtering web proxy server provides administrative control over the
content that may be relayed through the proxy. It is commonly used in commercial and
non-commercial organizations (especially schools) to ensure that Internet usage conforms
to acceptable use policy. However in some cases users who disagree with the policy can

figure out ways to revolt by bypassing a proxy (particularly a software-based one, by


downloading and using their own proxy).

39

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

Some common methods used for content filtering include: URL or DNS
blacklists, URL regex filtering, MIME filtering, or content keyword filtering. Some
products have been known to employ content analysis techniques to look for traits
commonly used by certain types of content providers.
A content filtering proxy will often support user authentication, to control web
access. It also usually produces logs, either to give detailed information about the URLs
accessed by specific users, or to monitor bandwidth usage statistics. It may also
communicate to daemon based and/or ICAP based antivirus software to provide security
against virus and other malware by scanning incoming content in real time before it
enters the network.

Anonymizing proxy server


An anonymous proxy server (sometimes called a web proxy) generally attempts
to anonymize web surfing. There are different varieties of anonymizers. One of the more
common variations is the open proxy. Because they are typically difficult to track, open
proxies are especially useful to those seeking online anonymity, from political dissidents
to computer criminals. Some users are merely interested in anonymity on principle, to
facilitate constitutional human rights of freedom of speech, for instance. The server
receives requests from the anonymizing proxy server, and thus does not receive
information about the end user's address. However, the requests are not anonymous to the
anonymizing proxy server, and so a degree of trust is present between that server and the
user. Many of them are funded through a continued advertising link to the user.
Access control: Some proxy servers implement a logon requirement. In large
organizations, authorized users must log on to gain access to the web. The organization
can thereby track usage to individuals.
Some anonymizing proxy servers may forward data packets with header lines such as
HTTP_VIA, HTTP_X_FORWARDED_FOR, or HTTP_FORWARDED, which may
reveal the IP address of the client. Other anonymizing proxy servers, known as elite or
high anonymity proxies, only include the REMOTE_ADDR header with the IP address of
the proxy server, making it appear that the proxy server is the client. A website could still
suspect a proxy is being used if the client sends packets which include a cookie from a
previous visit that did not use the high anonymity proxy server. Clearing cookies, and
possibly the cache, would solve this problem.

Hostile proxy
Proxies can also be installed in order to eavesdrop upon the dataflow between
client machines and the web. All accessed pages, as well as all forms submitted, can be
captured and analyzed by the proxy operator. For this reason, passwords to online
services (such as webmail and banking) should always be exchanged over a
cryptographically secured connection, such as SSL.

Intercepting proxy server

40

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

An intercepting proxy (also known as a "transparent proxy") combines a proxy server


with a gateway. Connections made by client browsers through the gateway are redirected
through the proxy without client-side configuration (or often knowledge).
Intercepting proxies are commonly used in businesses to prevent avoidance of acceptable
use policy, and to ease administrative burden, since no client browser configuration is
required.
It is often possible to detect the use of an intercepting proxy server by comparing the
external IP address to the address seen by an external web server, or by examining the
HTTP headers on the server side.

Transparent and non-transparent proxy server


The term "transparent proxy" is most often used incorrectly to mean "intercepting
proxy" (because the client does not need to configure a proxy and cannot directly detect
that its requests are being proxied). Transparent proxies can be implemented using
Cisco's WCCP (Web Cache Control Protocol). This proprietary protocol resides on the
router and is configured from the cache, allowing the cache to determine what ports and
traffic is sent to it via transparent redirection from the router. This redirection can occur
in one of two ways: GRE Tunneling (OSI Layer 3) or MAC rewrites (OSI Layer 2).
"A 'transparent proxy' is a proxy that does not modify the request or response
beyond what is required for proxy authentication and identification".
"A 'non-transparent proxy' is a proxy that modifies the request or response in
order to provide some added service to the user agent, such as group annotation
services, media type transformation, protocol reduction, or anonymity filtering".

Forced proxy
The term "forced proxy" is ambiguous. It means both "intercepting proxy"
(because it filters all traffic on the only available gateway to the Internet) and its exact
opposite, "non-intercepting proxy" (because the user is forced to configure a proxy in
order to access the Internet).
Forced proxy operation is sometimes necessary due to issues with the interception of TCP
connections and HTTP. For instance, interception of HTTP requests can affect the
usability of a proxy cache, and can greatly affect certain authentication mechanisms. This
is primarily because the client thinks it is talking to a server, and so request headers
required by a proxy are unable to be distinguished from headers that may be required by
an upstream server (esp authorization headers). Also the HTTP specification prohibits
caching of responses where the request contained an authorization header.

Suffix proxy
A suffix proxy server allows a user to access web content by appending the name of the
proxy server to the URL of the requested content (e.g. "en.wikipedia.org.6a.nl").

41

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

Suffix proxy servers are easier to use than regular proxy servers. The concept appeared in
2003 in form of the IPv6Gate and in 2004 in form of the Coral Content Distribution
Network.

Open proxy server


Because proxies might be used to abuse, system administrators have developed a
number of ways to refuse service to open proxies. Many IRC networks automatically test
client systems for known types of open proxy. Likewise, an email server may be
configured to automatically test e-mail senders for open proxies.
Groups of IRC and electronic mail operators run DNSBLs publishing lists of the IP
addresses of known open proxies, such as AHBL, CBL, NJABL, and SORBS.
The ethics of automatically testing clients for open proxies are controversial. Some
experts, such as Vernon Schryver, consider such testing to be equivalent to an attacker
portscanning the client host Others consider the client to have solicited the scan by
connecting to a server whose terms of service include testing.

Reverse proxy server


A reverse proxy is a proxy server that is installed in the neighborhood of one or
more web servers. All traffic coming from the Internet and with a destination of one of
the web servers goes through the proxy server. There are several reasons for installing
reverse proxy servers:

Encryption / SSL acceleration: when secure web sites are created, the SSL
encryption is often not done by the web server itself, but by a reverse proxy that is
equipped with SSL acceleration hardware. See Secure Sockets Layer.
Furthermore, a host can provide a single "SSL proxy" to provide SSL encryption
for an arbitrary number of hosts; removing the need for a separate SSL Server
Certificate for each host, with the downside that all hosts behind the SSL proxy
have to share a common DNS name or IP address for SSL connections.
Load balancing: the reverse proxy can distribute the load to several web servers,
each web server serving its own application area. In such a case, the reverse proxy
may need to rewrite the URLs in each web page (translation from externally
known URLs to the internal locations).
Serve/cache static content: A reverse proxy can offload the web servers by
caching static content like pictures and other static graphical content.
Compression: the proxy server can optimize and compress the content to speed up
the load time.
Spoon feeding: reduces resource usage caused by slow clients on the web servers
by caching the content the web server sent and slowly "spoon feeding" it to the
client. This especially benefits dynamically generated pages.
Security: the proxy server is an additional layer of defense and can protect against
some OS and WebServer specific attacks. However, it does not provide any
protection to attacks against the web application or service itself, which is
generally considered the larger threat.
42

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

Extranet Publishing: a reverse proxy server facing the Internet can be used to
communicate to a firewalled server internal to an organization, providing extranet
access to some functions while keeping the servers behind the firewalls. If used in
this way, security measures should be considered to protect the rest of your
infrastructure in case this server is compromised, as its web application is exposed
to attack from the Internet.

Circumventor
A circumventor is a method of defeating blocking policies implemented using
proxy servers. Ironically, most circumventors are also proxy servers, of varying degrees
of sophistication, which effectively implement "bypass policies".
A circumventor is a web-based page that takes a site that is blocked and
"circumvents" it through to an unblocked web site, allowing the user to view blocked
pages. A famous example is elgooG, which allowed users in China to use Google after it
had been blocked there. elgooG differs from most circumventors in that it circumvents
only one block.
A September 2007 report from Citizen Lab recommended Web based proxies
Proxify, StupidCensorship, and CGIProxy. Alternatively, users could partner with
individuals outside the censored network running Psiphon or Peacefire/Circumventor. A
more elaborate approach suggested was to run free tunneling software such as UltraSurf,
and FreeGate, or pay services Anonymizer and Ghost Surf. Also listed were free
application tunneling software Gpass and HTTP Tunnel, and pay application software
Relakks and Guardster. Lastly, anonymous communication networks JAP ANON, Tor,
and I2Poffer a range of possibilities for secure publication and browsing.
Students are able to access blocked sites (games, chatrooms, messenger, offensive
material, internet pornography, social networking, etc.) through a circumventor. As fast as
the filtering software blocks circumventors, others spring up. However, in some cases the
filter may still intercept traffic to the circumventor, thus the person who manages the
filter can still see the sites that are being visited.
Circumventors are also used by people who have been blocked from a web site.
Another use of a circumventor is to allow access to country-specific services, so
that Internet users from other countries may also make use of them. An example is
country-restricted reproduction of media and webcasting.
The use of circumventors is usually safe with the exception that circumventor
sites run by an untrusted third party can be run with hidden intentions, such as collecting
personal information, and as a result users are typically advised against running personal
data such as credit card numbers or passwords through a circumventor.
An example of one way to circumvent a content-filtering proxy server is by
tunnelling through to another proxy server, usually controlled by the user, which has
unrestricted access to the internet. This is often achieved by using a VPN type tunnel,

43

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

such as VPN itself or SSH, through a port left open by the proxy server to be
circumvented. Port 80 is almost always open to allow the use of HTTP, as is Port 443 to
allow the use of HTTPS. Through the use of encryption, tunnelling to a remote proxy
server, provided the remote proxy server is itself secure, is not only difficult to detect, but
also difficult to intercept.
In some network configurations, clients attempting to access the proxy server are
given different levels of access privilege on the grounds of their computer location or
even the MAC address of the network card. However, if one has access to a system with
higher access rights, they could use that system as a proxy server for which the other
clients use to access the original proxy server, consequently altering their access
privileges.

Content filter
Many work places, schools, and colleges restrict the web sites and online services
that are made available in their buildings. This is done either with a specialized proxy,
called a content filter (both commercial and free products are available), or by using a
cache-extension protocol such as ICAP, that allows plug-in extensions to an open caching
architecture.
Requests made to the open internet must first pass through an outbound proxy
filter. The web-filtering company provides a database of URL patterns (regular
expressions) with associated content attributes. This database is updated weekly by sitewide subscription, much like a virus filter subscription. The administrator instructs the
web filter to ban broad classes of content (such as sports, pornography, online shopping,
gambling, or social networking). Requests that match a banned URL pattern are rejected
immediately.
Assuming the requested URL is acceptable, the content is then fetched by the
proxy. At this point a dynamic filter may be applied on the return path. For example,
JPEG files could be blocked based on fleshtone matches, or language filters could
dynamically detect unwanted language. If the content is rejected then an HTTP fetch
error is returned and nothing is cached.
Most web filtering companies use an internet-wide crawling robot that assesses
the likelihood that a content is a certain type (i.e. "This content is 70% chance of porn,
40% chance of sports, and 30% chance of news" could be the outcome for one web
page). The resultant database is then corrected by manual labor based on complaints or
known flaws in the content-matching algorithms.
Web filtering proxies are not able to peer inside secure sockets HTTP transactions. As a
result, users wanting to bypass web filtering will typically search the internet for an open
and anonymous HTTPS transparent proxy. They will then program their browser to proxy
all requests through the web filter to this anonymous proxy. Those requests will be
encrypted with https. The web filter cannot distinguish these transactions from, say, a
legitimate access to a financial website. Thus, content filters are only effective against
unsophisticated users.

44

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

A special case of web proxies is "CGI proxies". These are web sites that allow a
user to access a site through them. They generally use PHP or CGI to implement the
proxy functionality. These types of proxies are frequently used to gain access to web sites
blocked by corporate or school proxies. Since they also hide the user's own IP address
from the web sites they access through the proxy, they are sometimes also used to gain a
degree of anonymity, called "Proxy Avoidance".

Risks of using anonymous proxy servers


In using a proxy server (for example, anonymizing HTTP proxy), all data sent to
the service being used (for example, HTTP server in a website) must pass through the
proxy server before being sent to the service, mostly in unencrypted form. It is therefore a
feasible risk that a malicious proxy server may record everything sent: including
unencrypted logins and passwords.
By chaining proxies which do not reveal data about the original requester, it is
possible to obfuscate activities from the eyes of the user's destination. However, more
traces will be left on the intermediate hops, which could be used or offered up to trace the
user's activities. If the policies and administrators of these other proxies are unknown, the
user may fall victim to a false sense of security just because those details are out of sight
and mind.
The bottom line of this is to be wary when using anonymizing proxy servers, and
only use proxy servers of known integrity (e.g., the owner is known and trusted, has a
clear privacy policy, etc.), and never use proxy servers of unknown integrity. If there is no
choice but to use unknown proxy servers, do not pass any private information (unless it is
over an encrypted connection) through the proxy.
In what is more of an inconvenience than a risk, proxy users may find themselves
being blocked from certain Web sites, as numerous forums and Web sites block IP
addresses from proxies known to have spammed or trolled the site.

Firewall
.

45

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

An illustration of how a firewall works.

An example of a user interface for a firewall


A firewall is a part of a computer system or network that is designed to block
unauthorized access while permitting authorized communications. It is a device or set of
devices configured to permit, deny, encrypt, decrypt, or proxy all (in and out) computer
traffic between different security domains based upon a set of rules and other criteria.
Firewalls can be implemented in either hardware or software, or a combination of both.
Firewalls are frequently used to prevent unauthorized Internet users from accessing
private networks connected to the Internet, especially intranets. All messages entering or
leaving the intranet pass through the firewall, which examines each message and blocks
those that do not meet the specified security criteria.

There are several types of firewall techniques:

46

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

1. Packet filter: Looks at each packet entering or leaving the network and accepts or
rejects it based on user-defined rules. Packet filtering is fairly effective and
transparent to users, but it is difficult to configure. In addition, it is susceptible to
IP spoofing.
2. Application gateway: Applies security mechanisms to specific applications, such
as FTP and Telnet servers. This is very effective, but can impose a performance
degradation.
3. Circuit-level gateway: Applies security mechanisms when a TCP or UDP
connection is established. Once the connection has been made, packets can flow
between the hosts without further checking.
4. Proxy server: Intercepts all messages entering and leaving the network. The proxy
server effectively hides the true network addresses.

Function
A firewall is a dedicated appliance, or software running on a computer, which
inspects network traffic passing through it, and denies or permits passage based on a set
of rules.
A firewall's basic task is to regulate some of the flow of traffic between computer
networks of different trust levels. Typical examples are the Internet which is a zone with
no trust and an internal network which is a zone of higher trust. A zone with an
intermediate trust level, situated between the Internet and a trusted internal network, is
often referred to as a "perimeter network" or Demilitarized zone (DMZ).
A firewall's function within a network is similar to physical firewalls with fire
doors in building construction. In the former case, it is used to prevent network intrusion
to the private network. In the latter case, it is intended to contain and delay structural fire
from spreading to adjacent structures.
Without proper configuration, a firewall can often become worthless. Standard
security practices dictate a "default-deny" firewall ruleset, in which the only network
connections which are allowed are the ones that have been explicitly allowed.
Unfortunately, such a configuration requires detailed understanding of the network
applications and endpoints required for the organization's day-to-day operation. Many
businesses lack such understanding, and therefore implement a "default-allow" ruleset, in
which all traffic is allowed unless it has been specifically blocked. This configuration
makes inadvertent network connections and system compromise much more likely.

47

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

Internet standard
In computer network engineering, an Internet Standard (STD) is a normative
specification of a technology or methodology applicable to the Internet. Internet
Standards are created and published by the Internet Engineering Task Force (IETF).

Overview
An Internet Standard is a special Request for Comments (RFC) or set of RFCs.
An RFC that is to become a Standard or part of a Standard begins as an Internet Draft,
and is later (usually after several revisions) accepted and published by the RFC Editor as
a RFC and labeled a Proposed Standard. Later, an RFC is labelled a Draft Standard, and
finally a Standard. Collectively, these stages are known as the standards track, and are
defined in RFC 2026. The label Historic (sic) is applied to deprecated standards-track
documents or obsolete RFCs that were published before the standards track was
established.
Only the IETF, represented by the Internet Engineering Steering Group (IESG),
can approve standards-track RFCs. The definitive list of Internet Standards is maintained
in Internet Standards document STD 1: Internet Official Protocol Standards.[1]

Standardization process
Becoming a standard is a three step process within the IETF called Proposed
Standards, Draft Standards and finally Internet Standards. If an RFC is part of a proposal
that is on the standard track, then at the first stage, the standard is proposed and
subsequently organizations decide whether to implement this Proposed Standard. After
three separate implementations, more review and corrections are made to the RFC, and a
Draft Standard is created. At the final stage, the RFC becomes a Standard.

Proposed Standard
A Proposed Standard (PS) is generally stable, has resolved known design choices,
is believed to be well-understood, has received significant community review, and
appears to enjoy enough community interest to be considered valuable. However, further
experience might result in a change or even retraction of the specification before it
advances. Usually, neither implementation nor operational experience is required.

Draft Standard
A specification from which at least two independent and interoperable
implementations from different code bases have been developed, and for which sufficient
successful operational experience has been obtained, may be elevated to the Draft
Standard (DS) level.

48

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

A Draft Standard is normally considered to be a final specification, and changes


are likely to be made only to solve specific problems encountered. In most circumstances,
it is reasonable for vendors to deploy implementations of Draft Standards into a
disruption sensitive environment.

Standard
A specification for which significant implementation and successful operational
experience has been obtained may be elevated to the Internet Standard (STD) level. An
Internet Standard, which may simply be referred to as a Standard, is characterized by a
high degree of technical maturity and by a generally held belief that the specified
protocol or service provides significant benefit to the Internet community.
Generally Internet Standards cover interoperability of systems on the internet
through defining protocols, messages formats, schemas, and languages. The most
fundamental of the Standards are the ones defining the Internet Protocol.
All Internet Standards are given a number in the STD series - The first document
in this series, STD 1, describes the remaining documents in the series, and has a list of
Proposed Standards.
Each RFC is static; if the document is changed, it is submitted again and assigned
a new RFC number. If an RFC becomes an Internet Standard (STD), it is assigned an
STD number but retains its RFC number. When an Internet Standard is updated, its
number stays the same and it simply refers to a different RFC or set of RFCs. A given
Internet Standard, STD n, may be RFCs x and y at a given time, but later the same
standard may be updated to be RFC z instead. For example, in 2007 RFC 3700 was an
Internet StandardSTD 1and in May 2008 it was replaced with RFC 5000, so RFC
3700 changed to Historic status, and now STD 1 is RFC 5000. When STD 1 is updated
again, it will simply refer to a newer RFC, but it will still be STD 1. Note that not all
RFCs are standards-track documents, but all Internet Standards and other standards-track
documents are RFCs.

49

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

History of the World Wide Web

Today, the Web and the Internet allow connectivity from literally everywhere on earth
even ships at sea and in outer space.
The World Wide Web ("WWW" or simply the "Web") is a global information
medium which users can read and write via computers connected to the Internet. The
term is often mistakenly used as a synonym for the Internet itself, but the Web is a service
that operates over the Internet, as e-mail does. The history of the Internet dates back
significantly further than that of the World Wide Web.
The hypertext portion of the Web in particular has an intricate intellectual history;
notable influences and precursors include Vannevar Bush's Memex, IBM's Generalized
Markup Language, and Ted Nelson's Project Xanadu.
The concept of a home-based global information system goes at least as far back
as "A Logic Named Joe", a 1946 short story by Murray Leinster, in which computer
terminals, called "logics," were in every home. Although the computer system in the story
is centralized, the story captures some of the feeling of the ubiquitous information
explosion driven by the Web.

Development of the World Wide Web


In 1980, the Englishman Tim Berners-Lee, an independent contractor at the
European Organization for Nuclear Research (CERN), Switzerland, built ENQUIRE, as a
personal database of people and software models, but also as a way to play with
hypertext; each new page of information in ENQUIRE had to be linked to an existing
page.
50

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

In 1984 Berners-Lee returned to CERN, and considered its problems of


information presentation: physicists from around the world needed to share data, with no
common machines and no common presentation software. He wrote a proposal in March
1989 for "a large hypertext database with typed links", but it generated little interest. His
boss, Mike Sendall, encouraged Berners-Lee to begin implementing his system on a
newly acquired NeXT workstation. He considered several names, including Information
Mesh, The Information Mine (turned down as it abbreviates to TIM, the WWW's creator's
name) or Mine of Information (turned down because it abbreviates to MOI which is "Me"
in French), but settled on World Wide Web[1].
He found an enthusiastic collaborator in Robert Cailliau, who rewrote the
proposal (published on November 12, 1990) and sought resources within CERN.
Berners-Lee and Cailliau pitched their ideas to the European Conference on Hypertext
Technology in September 1990, but found no vendors who could appreciate their vision
of marrying hypertext with the Internet.
By Christmas 1990, Berners-Lee had built all the tools necessary for a working
Web: the HyperText Transfer Protocol (HTTP) 0.9, the HyperText Markup Language
(HTML), the first Web browser (named WorldWideWeb, which was also a Web editor),
the first HTTP server software (later known as CERN httpd), the first web server
(http://info.cern.ch), and the first Web pages that described the project itself. The browser
could access Usenet newsgroups and FTP files as well. However, it could run only on the
NeXT; Nicola Pellow therefore created a simple text browser that could run on almost
any computer. To encourage use within CERN, they put the CERN telephone directory on
the web previously users had had to log onto the mainframe in order to look up phone
numbers.
Paul Kunz from the Stanford Linear Accelerator Center visited CERN in May
1991, and was captivated by the Web. He brought the NeXT software back to SLAC,
where librarian Louise Addis adapted it for the VM/CMS operating system on the IBM
mainframe as a way to display SLACs catalog of online documents; this was the first
web server outside of Europe and the first in North America[2].
On August 6, 1991, Berners-Lee posted a short summary of the World Wide Web
project on the alt.hypertext newsgroup. This date also marked the debut of the Web as a
publicly available service on the Internet.
The WorldWideWeb (WWW) project aims to allow all links to be made to any
information anywhere. [...] The WWW project was started to allow high energy physicists to
share data, news, and documentation. We are very interested in spreading the web to other areas,
and having gateway servers for other data. Collaborators welcome!" from Tim Berners-Lee's
first message

An early CERN-related contribution to the Web was the parody band Les
Horribles Cernettes, whose promotional image is believed to be among the Web's first
five pictures[3].

51

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

Web server
The term web server or webserver can mean one of two things:
1. A computer program that is responsible for accepting HTTP requests from clients
(user agents such as web browsers), and serving them HTTP responses along with
optional data contents, which usually are web pages such as HTML documents
and linked objects (images, etc.).
2. A computer that runs a computer program as described above.

Common features
Although web server programs differ in detail, they all share some basic common
features.
1. HTTP: every web server program operates by accepting HTTP requests from the
client, and providing an HTTP response to the client. The HTTP response usually
consists of an HTML or XHTML document, but can also be a raw file, an image,
or some other type of document (defined by MIME-types). If some error is found
in client request or while trying to serve it, a web server has to send an error
response which may include some custom HTML or text messages to better
explain the problem to end users.
2. Logging: usually web servers have also the capability of logging some detailed
information, about client requests and server responses, to log files; this allows
the webmaster to collect statistics by running log analyzers on these files.
In practice many web servers also implement the following features:
1. Authentication, optional authorization request (request of user name and
password) before allowing access to some or all kind of resources.
2. Handling of static content (file content recorded in server's filesystem(s)) and
dynamic content by supporting one or more related interfaces (SSI, CGI, SCGI,
FastCGI, JSP,ColdFusion, PHP, ASP, WhizBase, ASP.NET, Server API such as
NSAPI, ISAPI, etc.).
3. HTTPS support (by SSL or TLS) to allow secure (encrypted) connections to the
server on the standard port 443 instead of usual port 80.
4. Content compression (i.e. by gzip encoding) to reduce the size of the responses
(to lower bandwidth usage, etc.).
5. Virtual hosting to serve many web sites using one IP address.
6. Large file support to be able to serve files whose size is greater than 2 GB on 32
bit OS.
7. Bandwidth throttling to limit the speed of responses in order to not saturate the
network and to be able to serve more clients.

52

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

Vendor

Apache

Product

Apache

Microsoft IIS

Google

GWS

nginx

nginx

lighttpd

lighttpd

Apache HTTP Server


The Apache HTTP Server, commonly referred to as Apache is a web server
notable for playing a key role in the initial growth of the World Wide Web and in 2009
became the first web server to surpass the 100 million web site milestone [2]. Apache was
the first viable alternative to the Netscape Communications Corporation web server
(currently known as Sun Java System Web Server), and has since evolved to rival other
Unix-based web servers in terms of functionality and performance. The majority of all
web servers using Apache are Linux web servers.
Apache is developed and maintained by an open community of developers under the
auspices of the Apache Software Foundation. The application is available for a wide
variety of operating systems, including Unix, GNU, FreeBSD, Linux, Solaris, Novell
NetWare, Mac OS X, Microsoft Windows, OS/2, TPF, and eComStation. Released under
the Apache License, Apache is characterized as free and open source software.
Since April 1996 Apache has been the most popular HTTP server on the World Wide
Web. As of March 2009 Apache served over 46% of all websites and over 66% of the
million busiest.[3]

Internet Information Services


Internet Information Services (IIS) - formerly called Internet Information
Server - is a set of Internet-based services for servers created by Microsoft for use with
Microsoft Windows. It is the world's second most popular web server in terms of overall
websites behind the industry leader Apache HTTP Server. As of April 2009 it served
29.27% of all websites according to Netcraft.[1] The services provided currently include
FTP, FTPS, SMTP, NNTP, and HTTP/HTTPS.

53

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

Google Web Server


Google Web Server (GWS) is the name for the web server software that Google
uses for their web infrastructure.
As of January 2009, it ranks #3 in the Netcraft Web Server Survey, with 3.78% of all
domains and 8.39% of all active sites. [1]
The latest version is 1.3.

Brief Background: Embedding ActiveX in web page


HTML was designed as a page description language for defining static pages. As originally
designed, when users connected to a web site, pages were sent to their browsers and displayed.
To change what was shown, a new page had to be loaded. If input was required from users, it
was sent back to the web server, processed there, and then new pages were sent back to the
users' browsers. No local processing or updates were possible.
With the advent of ActiveX comes the concept of active content. You can embed items that will
run on the user's machine in the HTML code that creates a web page. These items can
dynamically update their displays or validate user input without accessing the web server. An
ActiveX control is a modular piece of software that has its own small graphical interface and can
perform tasks, compute information, and communicate to other programs. They can be easily
used and reused by any ActiveX-capable program or language, such as Internet Explorer and
Visual Basic. For example, the FarPoint Technologies Input Pro product offers a suite of
user entry controls that can format and validate content as a user enters information into the
control.
When an ActiveX-capable browser encounters a Web page with one or more ActiveX controls, it
checks the user's local system registry to see if those controls already exist on the user's
computer. If they do exist, the browser displays the page and activates the controls. If the controls
are not already installed on the user's computer, the browser automatically finds and installs the
control over the Web. The browser knows where to find the control because the appropriate Web
site is coded into the tag that embeds the ActiveX control. By default, ActiveX controls are
downloaded into an ActiveX control cache located in the \Windows\occache directory.
ActiveX technology relies on the user's browser being able to run the embedded content, the
ActiveX control. For example, the first browser that had native support for ActiveX controls was
Microsoft's Internet Explorer 3.0.
For more information about ActiveX in general, see Resources for ActiveX Information.
Return to top

54

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

Embedding Active Content: The <OBJECT> Tag


HTML pages are made up of text separated by tags that define how the text should be displayed.
You can use specialized tags to display images or to provide a link to another page. Microsoft has
decided to use the <OBJECT> tag to place ActiveX controls in HTML pages.
The following example illustrates an object tag:
<OBJECT ID="fpBoolean1" CLASSID="CLSID:DD55D143-EBF7-11D0-88100000C0E5948C" CODEBASE="http://www.fpoint.com/max/inputpro.cab"> <PARAM
NAME="BorderStyle" VALUE="0"> <PARAM NAME="BorderColor" VALUE="2147483642"> <PARAM NAME="BorderWidth" VALUE="1"> <PARAM
NAME="BooleanStyle" VALUE="0"> <PARAM NAME="TextFalse" VALUE="FarPoint
Boolean"> </OBJECT>
The tag has the following parameters:
ID=

A name for the object. The name should be unique among all
other objects on the page.

CLASSID=

A class ID number. Every ActiveX control has a unique class ID


that was encoded into it during development. The browser uses
this number to determine which control to load.
This number must be exactly correct or the control will not load.
Thus, it is preferable to cut and paste these numbers into your
object tag or to use a tool such as the ActiveX Control Pad to
insert them. For more information, see "Using the ActiveX Control
Pad."

CODEBASE=

URL referring to where the ActiveX control can be acquired.


When the page is loaded into the user's system, the browser
checks the registry to determine if the system has the ActiveX
control referenced by the CLASSID. If it does, then the local copy
is used. Otherwise, the browser attempts to download the control
from the URL designated by the CODEBASE tag.
For details on the intricacies of code downloading, see
Microsoft's code download specification.

PARAM NAME="x"
VALUE="y"

Optional parameters to set properties of the ActiveX control when


it is loaded. Each is expressed as a property NAME and a VALUE
to set it to. Once the control is loaded, it is given these property
settings by the browser. Which settings are supported depends
on the ActiveX control.

DATA=

An optional parameter providing binary data that sets properties


and provides information about the control.

Close the object tag using the (</OBJECT>) tag after the parameter list.

55

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

UNIT II

What is VBScript?

VBScript is a scripting language


A scripting language is a lightweight programming language
VBScript is a light version of Microsoft's programming language Visual Basic

How Does it Work?


When a VBScript is inserted into an HTML document, the Internet browser will read the HTML and interpret the VBScript.
The VBScript can be executed immediately, or at a later event.

The HTML <script> tag is used to insert a VBScript into an HTML page.

Put a VBScript into an HTML Page


The example below shows how to use VBSript to write text on a web page:

Example (IE Only)


<html>
<body>
<script type="text/vbscript">
document.write("Hello World!")
</script>
</body>
</html>

The example below shows how to add HTML tags to the VBScript:

Example (IE Only)


<html>
<body>
<script type="text/vbscript">
document.write("<h1>Hello World!</h1>")
</script>
</body>
</html>

Example Explained
To insert a VBScript into an HTML page, we use the <script> tag. Inside the <script> tag we use the type attribute to define
the scripting language.

56

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY


So, the <script type="text/vbscript"> and </script> tells where the VBScript starts and ends:

<html>
<body>
<script type="text/vbscript">
...
</script>
</body>
</html>
The document.write command is a standard VBScript command for writing output to a page.
By entering the document.write command between the <script> and </script> tags, the browser will recognize it as a VBScript
command and execute the code line. In this case the browser will write Hello World! to the page:

<html>
<body>
<script type="text/vbscript">
document.write("Hello World!")
</script>
</body>
</html>

How to Handle Simple Browsers


Browsers that do not support VBScript, will display VBScript as page content.
To prevent them from doing this, the HTML comment tag should be used to "hide" the VBScript.
Just add an HTML comment tag <!-- before the first VBScript statement, and a --> (end of comment) after the last VBScript
statement, like this:

<html>
<body>
<script type="text/vbscript">
<!-document.write("Hello World!")
-->-->
</script>
</body>
</html

Where to Put the VBScript


VBScripts in a page will be executed immediately while the page loads into the browser. This is not always what we
want. Sometimes we want to execute a script when a page loads, other times when a user triggers an event.

Scripts in <head>

57

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY


Scripts to be executed when they are called, or when an event is triggered, go in the head section.
If you place a script in the head section, you will ensure that the script is loaded before anyone uses it.

Example (IE Only)


<html>
<head>
<script type="text/vbscript">
alert("Hello World!")
</script>
</head>
<body>
</body>
</html>

Scripts in <body>
Scripts to be executed when the page loads go in the body section.
If you place a script in the body section, it generates the content of a page.

Example (IE Only)


<html>
<head>
</head>
<body>
<script type="text/vbscript">
document.write("This message is written by VBScript")
</script>
</body>
</html>

Scripts in <head> and <body>


You can place an unlimited number of scripts in your document, so you can have scripts in both the body and the head
section.

<html>
<head>
<script type="text/vbscript">
....
</script>
</head>
<body>

58

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY


<script type="text/vbscript">
....
</script>

VBScript Variables
As with algebra, VBScript variables are used to hold values or expressions.
A variable can have a short name, like x, or a more descriptive name, like carname.
Rules for VBScript variable names:

Must begin with a letter


Cannot contain a period (.)
Cannot exceed 255 characters

In VBScript, all variables are of type variant, that can store different types of data.

Declaring (Creating) VBScript Variables


Creating variables in VBScript is most often referred to as "declaring" variables.
You can declare VBScript variables with the Dim, Public or the Private statement. Like this:

Dim x;
Dim carname;
Now you have created two variables. The name of the variables are "x" and "carname".
You can also declare variables by using its name in a script. Like this:

carname=some value
Now you have also created a variable. The name of the variable is "carname". However, this method is not a good practice,
because you can misspell the variable name later in your script, and that can cause strange results when your script is running.
If you misspell for example the "carname" variable to "carnime", the script will automatically create a new variable called
"carnime". To prevent your script from doing this, you can use the Option Explicit statement. This statement forces you to
declare all your variables with the dim, public or private statement.
Put the Option Explicit statement on the top of your script. Like this:

Option Explicit
Dim carname
carname=some value

59

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

Assigning Values to Variables


You assign a value to a variable like this:

carname="Volvo"
x=10
The variable name is on the left side of the expression and the value you want to assign to the variable is on the right. Now the
variable "carname" has the value of "Volvo", and the variable "x" has the value of "10".

Lifetime of Variables
How long a variable exists is its lifetime.
When you declare a variable within a procedure, the variable can only be accessed within that procedure. When the procedure
exits, the variable is destroyed. These variables are called local variables. You can have local variables with the same name in
different procedures, because each is recognized only by the procedure in which it is declared.
If you declare a variable outside a procedure, all the procedures on your page can access it. The lifetime of these variables
starts when they are declared, and ends when the page is closed.

VBScript Array Variables


An array variable is used to store multiple values in a single variable.
In the following example, an array containing 3 elements is declared:

Dim names(2)
The number shown in the parentheses is 2. We start at zero so this array contains 3 elements. This is a fixed-size array. You
assign data to each of the elements of the array like this:

names(0)="Tove"
names(1)="Jani"
names(2)="Stale"
Similarly, the data can be retrieved from any element using the index of the particular array element you want. Like this:

60

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY


mother=names(0)
You can have up to 60 dimensions in an array. Multiple dimensions are declared by separating the numbers in the parentheses
with commas. Here we have a two-dimensional array consisting of 5 rows and 7 columns:

Dim table(4,6)

VBScript Procedures
In VBScript, there are two kinds of procedures:

Sub procedure
Function procedure

VBScript Sub Procedures


A Sub procedure:

is a series of statements, enclosed by the Sub and End Sub statements


can perform actions, but does not return a value
can take arguments
without arguments, it must include an empty set of parentheses ()

Sub mysub()
some statements
End Sub
or
Sub mysub(argument1,argument2)
some statements
End Sub

VBScript Function Procedures


A Function procedure:

is a series of statements, enclosed by the Function and End Function statements


can perform actions and can return a value
can take arguments that are passed to it by a calling procedure
without arguments, must include an empty set of parentheses ()
returns a value by assigning a value to its name

Function myfunction()

61

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY


some statements
myfunction=some value
End Function
or
Function myfunction(argument1,argument2)
some statements
myfunction=some value
End Function

How to Call a Procedure


The line below shows how to call a Function procedure:

carname=findname()
Here you call a Function called "findname", the Function returns a value that will be stored in the variable "carname".
Or, you can do like this:

msgbox "Your car is a " & findname()


Here you also call a Function called "findname", the Function returns a value that will be displayed in the message box.
When you call a Sub procedure you can use the Call statement, like this:

Call MyProc(argument)
Or, you can omit the Call statement, like this:

MyProc argument

Conditional Statements
Conditional statements are used to perform different actions for different decisions.
In VBScript we have four conditional statements:

If statement - executes a set of code when a condition is true


If...Then...Else statement - select one of two sets of lines to execute
If...Then...ElseIf statement - select one of many sets of lines to execute
Select Case statement - select one of many sets of lines to execute

62

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

If...Then...Else
Use the If...Then...Else statement if you want to

execute some code if a condition is true


select one of two blocks of code to execute

If you want to execute only one statement when a condition is true, you can write the code on one line:

If i=10 Then msgbox "Hello"


There is no ..Else.. in this syntax. You just tell the code to perform one action if a condition is true (in this case If i=10).
If you want to execute more than one statement when a condition is true, you must put each statement on separate lines, and
end the statement with the keyword "End If":

If i=10 Then
msgbox "Hello"
i = i+1
End If
There is no ..Else.. in the example above either. You just tell the code to perform multiple actions if the condition is true.
If you want to execute a statement if a condition is true and execute another statement if the condition is not true, you must
add the "Else" keyword:

63

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY


Example (IE Only)
<html>
<body>
<script type="text/vbscript">
Function greeting()
i=hour(time)
If i < 10 Then
document.write("Good morning!")
Else
document.write("Have a nice day!")
End If
End Function
</script>
</head>
<body onload="greeting()">
</body>
</html>

In the example above, the first block of code will be executed if the condition is true, and the other block will be executed
otherwise (if i is greater than 10).

If...Then...ElseIf
You can use the If...Then...ElseIf statement if you want to select one of many blocks of code to execute:

64

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY


Example (IE Only)
<html>
<body>
<script type="text/vbscript">
Function greeting()
i=hour(time)
If i = 10 Then
document.write("Just started...!")
ElseIf i = 11 then
document.write("Hungry!")
ElseIf i = 12 then
document.write("Ah, lunch-time!")
ElseIf i = 16 then
document.write("Time to go home!")
Else
document.write("Unknown")
End If
End Function
</script>
</head>
<body onload="greeting()">
</body>
</html>

Select Case
You can also use the "Select Case" statement if you want to select one of many blocks of code to execute:

65

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY


Example (IE Only)
<html>
<body>
<script type="text/vbscript">
d=weekday(date)
Select Case d
Case 1
document.write("Sleepy Sunday")
Case 2
document.write("Monday again!")
Case 3
document.write("Just Tuesday!")
Case 4
document.write("Wednesday!")
Case 5
document.write("Thursday...")
Case 6
document.write("Finally Friday!")
Case else
document.write("Super Saturday!!!!")
End Select
</script>

Looping Statements
Looping statements are used to run the same block of code a specified number of times.
In VBScript we have four looping statements:

For...Next statement - runs code a specified number of times


For Each...Next statement - runs code for each item in a collection or each element of an
array
Do...Loop statement - loops while or until a condition is true
While...Wend statement - Do not use it - use the Do...Loop statement instead

For...Next Loop
Use the For...Next statement to run a block of code a specified number of times.
The For statement specifies the counter variable (i), and its start and end values. The Next statement increases the counter
variable (i) by one.

66

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY


Example
<html>
<body>
<script type="text/vbscript">
For i = 0 To 5
document.write("The number is " & i & "<br />")
Next
</script>
</body>
</html>

The Step Keyword


With the Step keyword, you can increase or decrease the counter variable by the value you specify.
In the example below, the counter variable (i) is INCREASED by two, each time the loop repeats.

For i=2 To 10 Step 2


some code
Next
To decrease the counter variable, you must use a negative Step value. You must specify an end value that is less than the start
value.
In the example below, the counter variable (i) is DECREASED by two, each time the loop repeats.

For i=10 To 2 Step -2


some code
Next

Exit a For...Next
You can exit a For...Next statement with the Exit For keyword.

For Each...Next Loop


A For Each...Next loop repeats a block of code for each item in a collection, or for each element of an array.

67

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY


Example
<html>
<body>
<script type="text/vbscript">
Dim cars(2)
cars(0)="Volvo"
cars(1)="Saab"
cars(2)="BMW"
For Each x In cars
document.write(x & "<br />")
Next
</script>
</body>
</html>

Do...Loop
If you don't know how many repetitions you want, use a Do...Loop statement.
The Do...Loop statement repeats a block of code while a condition is true, or until a condition becomes true.

Repeat Code While a Condition is True


You use the While keyword to check a condition in a Do...Loop statement.

Do While i>10
some code
Loop
If i equals 9, the code inside the loop above will never be executed.

Do
some code
Loop While i>10
The code inside this loop will be executed at least one time, even if i is less than 10.

Repeat Code Until a Condition Becomes True


You use the Until keyword to check a condition in a Do...Loop statement.

Do Until i=10
some code
Loop
If i equals 10, the code inside the loop will never be executed.

Do

68

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY


some code
Loop Until i=10
The code inside this loop will be executed at least one time, even if i is equal to 10.

Exit a Do...Loop
You can exit a Do...Loop statement with the Exit Do keyword.

Do Until i=10
i=i-1
If i<10 Then Exit Do
Loop
The code inside this loop will be executed as long as i is different from 10, and as long as i is greater than 10.

Date/Time Functions
Function

Description

CDate

Converts a valid date and time expression to the variant of subtype


Date

Date

Returns the current system date

DateAdd

Returns a date to which a specified time interval has been added

DateDiff

Returns the number of intervals between two dates

DatePart

Returns the specified part of a given date

DateSerial

Returns the date for a specified year, month, and day

DateValue

Returns a date

Day

Returns a number that represents the day of the month (between 1


and 31, inclusive)

FormatDateTime

Returns an expression formatted as a date or time

Hour

Returns a number that represents the hour of the day (between 0


and 23, inclusive)

IsDate

Returns a Boolean value that indicates if the evaluated expression


can be converted to a date

Minute

Returns a number that represents the minute of the hour (between 0


and 59, inclusive)

Month

Returns a number that represents the month of the year (between 1


and 12, inclusive)

MonthName

Returns the name of a specified month

Now

Returns the current system date and time

Second

Returns a number that represents the second of the minute


(between 0 and 59, inclusive)

Time

Returns the current system time

Timer

Returns the number of seconds since 12:00 AM

TimeSerial

Returns the time for a specific hour, minute, and second

TimeValue

Returns a time

Weekday

Returns a number that represents the day of the week (between 1


and 7, inclusive)

69

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY


WeekdayName

Returns the weekday name of a specified day of the week

Year

Returns a number that represents the year

Conversion Functions
Function

Description

Asc

Converts the first letter in a string to ANSI code

CBool

Converts an expression to a variant of subtype Boolean

CByte

Converts an expression to a variant of subtype Byte

CCur

Converts an expression to a variant of subtype Currency

CDate

Converts a valid date and time expression to the variant of subtype


Date

CDbl

Converts an expression to a variant of subtype Double

Chr

Converts the specified ANSI code to a character

CInt

Converts an expression to a variant of subtype Integer

CLng

Converts an expression to a variant of subtype Long

CSng

Converts an expression to a variant of subtype Single

CStr

Converts an expression to a variant of subtype String

Hex

Returns the hexadecimal value of a specified number

Oct

Returns the octal value of a specified number

Format Functions
Function

Description

FormatCurrency

Returns an expression formatted as a currency value

FormatDateTime

Returns an expression formatted as a date or time

FormatNumber

Returns an expression formatted as a number

FormatPercent

Returns an expression formatted as a percentage

Math Functions
Function

Description

Abs

Returns the absolute value of a specified number

Atn

Returns the arctangent of a specified number

Cos

Returns the cosine of a specified number (angle)

Exp

Returns e raised to a power

Hex

Returns the hexadecimal value of a specified number

Int

Returns the integer part of a specified number

Fix

Returns the integer part of a specified number

Log

Returns the natural logarithm of a specified number

Oct

Returns the octal value of a specified number

70

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY


Rnd

Returns a random number less than 1 but greater or equal to 0

Sgn

Returns an integer that indicates the sign of a specified number

Sin

Returns the sine of a specified number (angle)

Sqr

Returns the square root of a specified number

Tan

Returns the tangent of a specified number (angle)

Array Functions
Function

Description

Array

Returns a variant containing an array

Filter

Returns a zero-based array that contains a subset of a string array


based on a filter criteria

IsArray

Returns a Boolean value that indicates whether a specified variable is


an array

Join

Returns a string that consists of a number of substrings in an array

LBound

Returns the smallest subscript for the indicated dimension of an


array

Split

Returns a zero-based, one-dimensional array that contains a


specified number of substrings

UBound

Returns the largest subscript for the indicated dimension of an array

String Functions
Function

Description

InStr

Returns the position of the first occurrence of one string within


another. The search begins at the first character of the string

InStrRev

Returns the position of the first occurrence of one string within


another. The search begins at the last character of the string

LCase

Converts a specified string to lowercase

Left

Returns a specified number of characters from the left side of a


string

Len

Returns the number of characters in a string

LTrim

Removes spaces on the left side of a string

RTrim

Removes spaces on the right side of a string

Trim

Removes spaces on both the left and the right side of a string

Mid

Returns a specified number of characters from a string

Replace

Replaces a specified part of a string with another string a specified


number of times

Right

Returns a specified number of characters from the right side of a


string

Space

Returns a string that consists of a specified number of spaces

StrComp

Compares two strings and returns a value that represents the result
of the comparison

String

Returns a string that contains a repeating character of a specified


length

StrReverse

Reverses a string

71

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY


UCase

Converts a specified string to uppercase

Other Functions
Function

Description

CreateObject

Creates an object of a specified type

Eval

Evaluates an expression and returns the result

GetLocale

Returns the current locale ID

GetObject

Returns a reference to an automation object from a file

GetRef

Allows you to connect a VBScript procedure to a DHTML event on


your pages

InputBox

Displays a dialog box, where the user can write some input and/or
click on a button, and returns the contents

IsEmpty

Returns a Boolean value that indicates whether a specified variable


has been initialized or not

IsNull

Returns a Boolean value that indicates whether a specified


expression contains no valid data (Null)

IsNumeric

Returns a Boolean value that indicates whether a specified


expression can be evaluated as a number

IsObject

Returns a Boolean value that indicates whether the specified


expression is an automation object

LoadPicture

Returns a picture object. Available only on 32-bit platforms

MsgBox

Displays a message box, waits for the user to click a button, and
returns a value that indicates which button the user clicked

RGB

Returns a number that represents an RGB color value

Round

Rounds a number

ScriptEngine

Returns the scripting language in use

ScriptEngineBuildVersion

Returns the build version number of the scripting engine in use

ScriptEngineMajorVersion

Returns the major version number of the scripting engine in use

ScriptEngineMinorVersion

Returns the minor version number of the scripting engine in use

SetLocale

Sets the locale ID and returns the previous locale ID

TypeName

Returns the subtype of a specified variable

VarType

Returns a value that indicates the subtype of a specified variable

72

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

EXAMPLES
Examples For Procedure
<html>
<head>
<script type="text/vbscript">
Sub mySub()
msgbox("This is a Sub procedure")
End Sub
</script>
</head>
<body>
<script type="text/vbscript">
Call mySub()
</script>
<p>A Sub procedure does not return a result.</p>
</body>
</html>
<html>
Examples For Procedure
<head>
<script type="text/vbscript">
Function myFunction()
myFunction = "BLUE"
End Function
</script>
</head>
<body>
<script type="text/vbscript">
document.write("My favorite color is " & myFunction())
</script>
<p>A Function procedure can return a result.</p>
</body>
</html>

73

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

Weekday Example
<html>
<body>
<p>VBScripts' function <b>WeekdayName</b> is used to get a weekday:</p>
<script type="text/vbscript">
document.write("<p>")
document.write(WeekDayName(1))
document.write("<br />")
document.write(WeekDayName(2))
document.write("</p><p>")
document.write("Get the abbreviated name of a weekday:")
document.write("<br />")
document.write(WeekDayName(1,True))
document.write("<br />")
document.write(WeekDayName(2,True))
document.write("</p><p>")
document.write("Get the current weekday:")
document.write("<br />")
document.write(WeekdayName(weekday(Date)))
document.write("<br />")
document.write(WeekdayName(weekday(Date), True))
document.write("</p>")
</script>
</body>
</html>
Example for Format Date, time
<html>
<body>
<script type="text/vbscript">
document.write(FormatDateTime(Date(),vbGeneralDate))
document.write("<br />")

74

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

document.write(FormatDateTime(Date(),vbLongDate))
document.write("<br />")
document.write(FormatDateTime(Date(),vbShortDate))
document.write("<br />")
document.write(FormatDateTime(Now(),vbLongTime))
document.write("<br />")
document.write(FormatDateTime(Now(),vbShortTime))
</script>
<p>Syntax for FormatDateTime: FormatDateTime(Date,namedformat).</p>
</body>
</html>
Return a Specified number of Char from String
<html>
<body>
<script type="text/vbscript">
sometext="Welcome to our Web Site!!"
document.write(Mid(sometext, 9, 2))
</script>
</body>
</html>
Replace String
<html>
<body>
<script type="text/vbscript">
sometext="Welcome to this Web!!"
document.write(Replace(sometext, "Web", "Page"))
</script>
</body>
</html>

Unit III

Report formatting in PERL


75

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY


Perl uses a writing template called a 'format' to output reports. To use the format feature of Perl, you must:

Define a Format
Pass the data that will be displayed on the format
Invoke the Format

Define a Format
Following is the syntax to define a Perl format

format FormatName =
fieldline
value_one, value_two, value_three
fieldline
value_one, value_two
.

FormatName represents the name of the format. The fieldline is the specific way the data should be formatted. The
values lines represent the values that will be entered into the field line. You end the format with a single period.

fieldline can contain any text or fieldholders. Fieldholders hold space for data that will be placed there at a later date.
A fieldholder has the format:

@<<<<
This fieldholder is left-justified, with a field space of 5. You must count the @ sign and the < signs to know the number of
spaces in the field. Other field holders include:

@>>>> right-justified
@|||| centered
@####.## numeric field holder
@* multiline field holder
An example format would be:

format EMPLOYEE =
===================================
@<<<<<<<<<<<<<<<<<<<<<< @<<
$name $age
@#####.##
$salary
===================================
.
In this example $name would be written as left justify within 22 character spaces and after that age will be written in two
spaces.

76

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

Invoke the Format to write Data


In order to invoke this format declaration we would use the write keyword:

write EMPLOYEE; #send to the output


The problem is that the format name is usually the name of an open file handle, and the write statement will send the output to
this file handle. As we want the data sent to the STDOUT, we must associate EMPLOYEE with the STDOUT filehandle. First,
however, we must make sure that that STDOUT is our selected file handle, using the select() function

select(STDOUT);
We would then associate EMPLOYEE with STDOUT by setting the new format name with STDOUT, using the special
variable $~

$~ = "EMPLOYEE";
When we now do a write(), the data would be sent to STDOUT. Remember: if you didn't have STDOUT set as your default
file handle, you could revert back to the original file handle by assigning the return value of select to a scalar value, and using
select along with this scalar variable after the special variable is assigned the format name, to be associated with STDOUT.
The above example will generate a report in the following format

Kirsten
Mohammad
Suhi
Namrat

12
35
15
10

Defining a Report Header


Everything looks fine. But you would be interested in adding a header to your report. This header will be printed on top of
each page. It is very simple to do this. Apart from defining a template you would have to define a header which will have same
name but appended with _TOP keyword as follows

format EMPLOYEE_TOP =
-----------------------Name
Age
-----------------------.
Now your report will look like

-----------------------Name
Age
-----------------------Kirsten
12
Mohammad
35
Suhi
15

77

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY


Namrat

10

Defining a Pagination & Number of Lines on a Page


What about if your report is taking more than one page ? You have a solution for that. Use $% vairable along with header as
follows

format EMPLOYEE_TOP =
-----------------------Name
Age
-----------------------.

Page @<
$%

Now your output will look like

-----------------------Name
Age
-----------------------Kirsten
12
Mohammad
35
Suhi
15
Namrat
10

Page 1

You can set the number of lines per page using special variable $= ( or $FORMAT_LINES_PER_PAGE ) By default $= will
be 60

Defining a Report Footer


One final thing is left which is footer. Very similar to header, you can define a footer and it will be written after each page.
Here you will use _BOTTOM keyword instead of _TOP.

format EMPLOYEE_BOTTOM =
End of Page @<
$%
.
This will give you following result

-----------------------Name
Age
-----------------------Kirsten
12
Mohammad
35
Suhi
15
Namrat
10
End of Page 1

Page 1

78

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

Object Oriented Programming in PERL


Before we start Object Oriented concept of perl, lets understand references and anonymous arrays and hashes

References
A reference is, exactly as the name suggests, a reference or pointer to another object.
There are two types of references: symbolic and hard.
A symbolic reference enables you to refer to a variable by name, using the value of another variable. For example, if
the variable $foo contains the string "bar", the symbolic reference to $foo refers to the variable $bar.

A hard reference refers to the actual data contained in a data structure.


Creating Hard References
The unary backslash operator is used to create a reference to a named variable or subroutine, for example:

$foo = 'Bill';
$fooref = \$foo;
The $fooref variable now contains a hard reference to the $foo variable. You can do the same with other variables:

$array = \@ARGV;
$hash = \%ENV;
$glob = \*STDOUT;
To create a reference to a subroutine:

sub foo { print "foo" };


$foosub = \&foo;

Anonymous Arrays
When you create a reference to an array directly - that is, without creating an intervening named array - you are creating an
anonymous array.
Creating an anonymous array is easy:

$array = [ 'Bill', 'Ben, 'Mary' ];


This line assigns an array, indicated by the enclosing square brackets instead of the normal parentheses, to the scalar $array.
The values on the right side of the assignment make up the array, and the left side contains the reference to this array.

79

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY


You can create more complex structures by nesting arrays:

@arrayarray = ( 1, 2, [1, 2, 3]);


The @arrayarray now contains three elements; the third element is a reference to an anonymous array of three elements.

Anonymous Hashes
Anonymous hashes are similarly easy to create, except you use braces instead of square brackets:

$hash = { 'Man' => 'Bill',


'Woman' => 'Mary,
'Dog' => 'Ben'
};

Dereferencing
The most direct way of dereferencing a reference is to prepend the corresponding data type character ($ for scalars, @ for
arrays, % for hashes, and & for subroutines) that you are expecting in front of the scalar variable containing the reference. For
example, to dereference a scalar reference $foo, you would access the data as $$foo. Other examples are:

$array = \@ARGV;
# Create reference
$hash = \%ENV;
# Create reference
$glob = \*STDOUT;
# Create reference
$foosub = \&foo;
# Create reference
push (@$array, "From humans");
$$array[0] = 'Hello'
$$hash{'Hello'} = 'World';
&$foosub;
print $glob "Hello World!\n";

to
to
to
to

array
hash
typeglob
subroutine

Object Basics
There are three main terms, explained from the point of view of how Perl handles objects. The terms are object, class, and
method.

Within Perl, an object is merely a reference to a data type that knows what class it belongs to. The object is stored as
a reference in a scalar variable. Because a scalar only contains a reference to the object, the same scalar can hold
different objects in different classes.
A class within Perl is a package that contains the corresponding methods required to create and manipulate objects.

A method within Perl is a subroutine, defined with the package. The first argument to the method is an object
reference or a package name, depending on whether the method affects the current object or the class.
Perl provides a bless() function which is used to return a reference and which becomes an object.

Defining a Class
Its very simple to define a class. In Perl, a class is corresponds to a Package.To create a class in Perl, we first build a package.
A package is a self-contained unit of user-defined variables and subroutines, which can be re-used over and over again. They
provide a separate namespace within a Perl program that keeps subroutines and variables from conflicting with those in other
packages.

80

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY


To declare a class named Person in Perl we do:

package Person;
The scope of the package definition extends to the end of the file, or until another package keyword is encountered.

Creating and Using Objects


To create an instance of a class (an object) we need an object constructor. This constructor is a method defined within the
package. Most programmers choose to name this object constructor method new, but in Perl one can use any name.
One can use any kind of Perl variable as an object in Perl. Most Perl programmers choose either references to arrays or hashes.
Let's create our constructor for our Person class using a Perl hash reference;
When creating an object, you need to supply a constructor. This is a subroutine within a package that returns an object
reference. The object reference is created by blessing a reference to the package's class. For example:

package Person;
sub new
{
my $class = shift;
my $self = {
_firstName => shift,
_lastName => shift,
_ssn
=> shift,
};
# Print all the values just for clarification.
print "First Name is $self->{_firstName}\n";
print "Last Name is $self->{_lastName}\n";
print "SSN is $self->{_ssn}\n";
bless $self, $class;
return $self;
}
Every method of a class passes first argument as class name. So in the above example class name would be "Person". You can
try this out by printing value of $class. Next rest of the arguments will be rest of the arguments passed to the method.
Now Let us see how to create an Object

$object = new Person( "Mohammad", "Saleem", 23234345);


You can use simple hash in your consturctor if you don't want to assign any value to any class variable. For example

package Person;
sub new
{
my $class = shift;
my $self = {};
bless $self, $class;
return $self;
}

Defining Methods

81

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY


Other object-oriented languages have the concept of security of data to prevent a programmer from changing an object data
directly and so provide accessor methods to modify object data. Perl does not have private variables but we can still use the
concept of helper functions methods and ask programmers to not mess with our object innards.
Lets define a helper method to get person first name:

sub getFirstName {
return $self->{_firstName};
}
Another helper function to set person first name:

sub setFirstName {
my ( $self, $firstName ) = @_;
$self->{_firstName} = $firstName if defined($firstName);
return $self->{_firstName};
}
Lets have a look into complete example: Keep Person package and helper functions into Person.pm file

#!/usr/bin/perl
package Person;
sub new
{
my $class = shift;
my $self = {
_firstName => shift,
_lastName => shift,
_ssn
=> shift,
};
# Print all the values just for clarification.
print "First Name is $self->{_firstName}\n";
print "Last Name is $self->{_lastName}\n";
print "SSN is $self->{_ssn}\n";
bless $self, $class;
return $self;
}
sub setFirstName {
my ( $self, $firstName ) = @_;
$self->{_firstName} = $firstName if defined($firstName);
return $self->{_firstName};
}
sub getFirstName {
my( $self ) = @_;
return $self->{_firstName};
}
1;
Now create Person object in mail.pl fileas follows

#!/usr/bin/perl
use Person;

82

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY


$object = new Person( "Mohammad", "Saleem", 23234345);
# Get first name which is set using constructor.
$firstName = $object->getFirstName();
print "Before Setting First Name is : $firstName\n";
# Now Set first name using helper function.
$object->setFirstName( "Mohd." );
# Now get first name set by helper function.
$firstName = $object->getFirstName();
print "Before Setting First Name is : $firstName\n";
This will produce following result
First Name is Mohammad
Last Name is Saleem
SSN is 23234345
Before Setting First Name is : Mohammad
Before Setting First Name is : Mohd.

Inheritance
Object-oriented programming sometimes involves inheritance. Inheritance simply means allowing one class called the Child
to inherit methods and attributes from another, called the Parent, so you don't have to write the same code again and again. For
example, we can have a class Employee which inherits from Person. This is referred to as an "isa" relationship because an
employee is a person. Perl has a special variable, @ISA, to help with this. @ISA governs (method) inheritance.
Following are noteable points while using inheritance

Perl searches the class of the specified object for the specified object.
Perl searches the classes defined in the object class's @ISA array.
If no method is found in steps 1 or 2, then Perl uses an AUTOLOAD subroutine, if one is found in the @ISA tree.
If a matching method still cannot be found, then Perl searches for the method within the UNIVERSAL class
(package) that comes as part of the standard Perl library.

If the method still hasn't been found, then Perl gives up and raises a runtime exception.
So to create a new Employee class that will inherit methods and attributes from our Person class, we simply code: Keep this
code into Employee.pm

#!/usr/bin/perl
package Employee;
use Person;
use strict;
our @ISA = qw(Person);

# inherits from Person

Now Employee Class has all the methods and attributes inherited from Person class and you can use it as follows: Use main.pl
file to test it

#!/usr/bin/perl
use Employee;

83

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY


$object = new Employee( "Mohammad", "Saleem", 23234345);
# Get first name which is set using constructor.
$firstName = $object->getFirstName();
print "Before Setting First Name is : $firstName\n";
# Now Set first name using helper function.
$object->setFirstName( "Mohd." );
# Now get first name set by helper function.
$firstName = $object->getFirstName();
print "After Setting First Name is : $firstName\n";
This will produce following result
First Name is Mohammad
Last Name is Saleem
SSN is 23234345
Before Setting First Name is : Mohammad
Before Setting First Name is : Mohd.

Method Overriding
The child class Employee inherits all the methods from parent class Person. But if you would like to override those methods in
your child class then you can do it by givig your implementation. You can add your additional functions in child class. It can
done as follows: modify Employee.pm file

#!/usr/bin/perl
package Employee;
use Person;
use strict;
our @ISA = qw(Person);

# inherits from Person

# Override constructor
sub new {
my ($class) = @_;
# Call the constructor of the parent class, Person.
my $self = $class->SUPER::new( $_[1], $_[2], $_[3] );
# Add few more attributes
$self->{_id}
= undef;
$self->{_title} = undef;
bless $self, $class;
return $self;
}
# Override helper function
sub getFirstName {
my( $self ) = @_;
# This is child class function.
print "This is child class helper function\n";
return $self->{_firstName};
}
# Add more methods
sub setLastName{
my ( $self, $lastName ) = @_;
$self->{_lastName} = $lastName if defined($lastName);

84

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY


return $self->{_lastName};
}
sub getLastName {
my( $self ) = @_;
return $self->{_lastName};
}
1;
Now put following code into main.pl and execute it.

#!/usr/bin/perl
use Employee;
$object = new Employee( "Mohammad", "Saleem", 23234345);
# Get first name which is set using constructor.
$firstName = $object->getFirstName();
print "Before Setting First Name is : $firstName\n";
# Now Set first name using helper function.
$object->setFirstName( "Mohd." );
# Now get first name set by helper function.
$firstName = $object->getFirstName();
print "After Setting First Name is : $firstName\n";
This will produce following result
First Name is Mohammad
Last Name is Saleem
SSN is 23234345
This is child class helper function
Before Setting First Name is : Mohammad
This is child class helper function
After Setting First Name is : Mohd.

Default Autoloading
Perl offers a feature which you would not find any many other programming languages: a default subroutine.
If you define a function called AUTOLOAD() then any calls to undefined subroutines will call AUTOLOAD() function. The
name of the missing subroutine is accessible within this subroutine as $AUTOLOAD. This function is very useful for error
handling purpose. Here is an example to implement AUTOLOAD, you can implement this function in your way.

sub AUTOLOAD
{
my $self = shift;
my $type = ref ($self) || croak "$self is not an object";
my $field = $AUTOLOAD;
$field =~ s/.*://;
unless (exists $self->{$field})
{
croak "$field does not exist in object/class $type";
}
if (@_)

85

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY


{
return $self->($name) = shift;
}
else
{
return $self->($name);
}
}

Destructors and Garbage Collection


If you have programmed using objects before, then you will be aware of the need to create a .destructor. to free the memory
allocated to the object when you have finished using it. Perl does this automatically for you as soon as the object goes out of
scope.
In case you want to implement your destructore which should take care of closing files or doing some extra processing then
you need to define a special method called DESTROY. This method will be called on the object just before Perl frees the
memory allocated to it. In all other respects, the DESTROY method is just like any other, and you can do anything you like
with the object in order to close it properly.
A destructor method is simply a member function (subroutine) named DESTROY which will be automatically called

When the object reference's variable goes out of scope.


When the object reference's variable is undef-ed
When the script terminates
When the perl interpreter terminates

For Example:

package MyClass;
...
sub DESTROY
{
print "
MyClass::DESTROY called\n";
}

Another OOP Example


Here is another nice example which will help you to understand Object Oriented Concepts of Perl. Put this source code into
any file and execute it.

#!/usr/bin/perl
# Following is the implementation of simple Class.
package MyClass;
sub new
{
print "
MyClass::new called\n";
my $type = shift;
# The package/type name
my $self = {};
# Reference to empty hash
return bless $self, $type;
}
sub DESTROY
{

86

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY


print "

MyClass::DESTROY called\n";

}
sub MyMethod
{
print "
MyClass::MyMethod called!\n";
}
# Following is the implemnetation of Inheritance.
package MySubClass;
@ISA = qw( MyClass );
sub new
{
print "
MySubClass::new called\n";
my $type = shift;
# The package/type name
my $self = MyClass->new;
# Reference to empty hash
return bless $self, $type;
}
sub DESTROY
{
print "
}

MySubClass::DESTROY called\n";

sub MyMethod
{
my $self = shift;
$self->SUPER::MyMethod();
print "
MySubClass::MyMethod called!\n";
}
# Here is the main program using above classes.
package main;
print "Invoke MyClass method\n";
$myObject = MyClass->new();
$myObject->MyMethod();
print "Invoke MySubClass method\n";
$myObject2 = MySubClass->new();
$myObject2->MyMethod();
print "Create a scoped object\n";
{
my $myObject2 = MyClass->new();
}
# Destructor is called automatically here
print "Create and undef an object\n";
$myObject3 = MyClass->new();
undef $myObject3;
print "Fall off the end of the script...\n";
# Remaining destructors are called automatically here

87

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

PERL-CGI Programming & Web Programming with PERL script

What is CGI ?
The Common Gateway Interface, or CGI, is a set of standards that define how information is exchanged between
the web server and a custom script.

The CGI specs are currently maintained by the NCSA and NCSA defines CGI is as follows:
The Common Gateway Interface, or CGI, is a standard for external gateway programs to interface with information
servers such as HTTP servers.

The current version is CGI/1.1 and CGI/1.2 is under progress.


Web Browsing
To understand the concept of CGI, lets see what happens when we click a hyper link to browse a particular web page or URL.

Your browser contacts the HTTP web server and demand for the URL ie. filename.
Web Server will parse the URL and will look for the filename in if it finds that file then sends back to the browser
otherwise sends an error message indicating that you have requested a wrong file.

Web browser takes response from web server and displays either the received file or error message.
However, it is possible to set up the HTTP server so that whenever a file in a certain directory is requested that file is not sent
back; instead it is executed as a program, and whatever that program outputs is sent back for your browser to display. This
function is called the Common Gateway Interface or CGI and the programs are called CGI scripts. These CGI programs can
be a PERL Script, Shell Script, C or C++ program etc.

88

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY


CGI Architecture Diagram

Web Server Support & Configuration


Before you proceed with CGI Programming, make sure that your Web Server supports CGI and it is
configured to handle CGI Programs. All the CGI Programs be executed by the HTTP server are kept
in a pre-configured directory. This directory is called CGI Directory and by convention it is named as
/cgi-bin. By convention PERL CGI files will have extention as .cgi.

First CGI Program


Here is a simple link which is linked to a CGI script called hello.cgi. This file is being kept in /cgi-bin/ directory and it has
following content. Before running your CGI program make sure you have chage mode of file using chmod 755 hello.cgi
UNIX command.

#!/usr/bin/perl
print
print
print
print
print
print
print
print
print

"Content-type:text/html\r\n\r\n";
'<html>';
'<head>';
'<title>Hello Word - First CGI Program</title>';
'</head>';
'<body>';
'<h2>Hello Word! This is my first CGI program</h2>';
'</body>';
'</html>';

1;
If you click hello.cgi then this produces following output:

Hello Word! This is my first CGI program

This hello.cgi script is a simple PERL script which is writing its output on STDOUT file ie. screen.
There is one important and extra feature available which is first line to be printed Contenttype:text/html\r\n\r\n. This line is sent back to the browser and specifiy the content type to be
displayed on the browser screen. Now you must have undertood basic concept of CGI and you can
write many complicated CGI programs using PERL. This script can interact with any other exertnal
system also to exchange information such as RDBMS.

HTTP Header
89

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY


The line Content-type:text/html\r\n\r\n is part of HTTP header which is sent to the browser to understand the content. All
the HTTP header will be in the following form

HTTP Field Name: Field Content


For Example
Content-type:text/html\r\n\r\n
There are few other important HTTP headers which you will use frequently in your CGI Programming.

Header

Description

Content-type: String

A MIME string defining the format of the file being returned. Example is
Content-type:text/html

Expires: Date String

The date the information becomes invalid. This should be used by the
browser to decide when a page needs to be refreshed. A valid date string
should be in the format 01 Jan 1998 12:00:00 GMT.

Location: URL String

The URL that should be returned instead of the URL requested. You can
use this filed to redirect a request to any file.

Last-modified: String

The date of last modification of the resource.

Content-length: String

The length, in bytes, of the data being returned. The browser uses this
value to report the estimated download time for a file.

Set-Cookie: String

Set the cookie passed through the string

CGI Environment Variables


All the CGI program will have access to the following environment variables. These variables play an important role while
writing any CGI program.
Variable Name

Description

CONTENT_TYPE

The data type of the content. Used when the client is sending attached
content to the server. For example file upload etc.

CONTENT_LENGTH

The length of the query information. It's available only for POST requests

HTTP_COOKIE

Return the set cookies in the form of key & value pair.

HTTP_USER_AGENT

The User-Agent request-header field contains information about the user


agent originating the request. Its name of the web browser.

PATH_INFO

The path for the CGI script.

QUERY_STRING

The URL-encoded information that is sent with GET method request.

REMOTE_ADDR

The IP address of the remote host making the request. This can be useful
for logging or for authentication purpose.

REMOTE_HOST

The fully qualified name of the host making the request. If this information
is not available then REMOTE_ADDR can be used to get IR address.

REQUEST_METHOD

The method used to make the request. The most common methods are GET

90

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY


and POST.
SCRIPT_FILENAME

The full path to the CGI script.

SCRIPT_NAME

The name of the CGI script.

SERVER_NAME

The server's hostname or IP Address

SERVER_SOFTWARE

The name and version of the software the server is running.

Here is small CGI program to list out all the CGI variables. Click this link to see the result Get Environment

#!/usr/bin/perl
print "Content-type: text/html\n\n";
print "<font size=+1>Environment</font>\n";
foreach (sort keys %ENV)
{
print "<b>$_</b>: $ENV{$_}<br>\n";
}
1;

How To Raise a "File Download" Dialog Box ?


Sometime it is desired that you want to give option where a use will click a link and it will pop up a "File Download" box to
the user in stead of displaying actual content. This is very easy and will be achived through HTTP header.

This HTTP header will be different from the header mentioned in previous section.
For example,if you want make a FileName file downloadable from a given link then its syntax will be as follows.

#!/usr/bin/perl
# HTTP Header
print "Content-Type:application/octet-stream; name=\"FileName\"\r\n";
print "Content-Disposition: attachment; filename=\"FileName\"\r\n\n";
# Actual File Content will go hear.
open( FILE, "<FileName" );
while(read(FILE, $buffer, 100) )
{
print("$buffer");
}

GET and POST Methods


You must have come across many situations when you need to pass some information from your browser to web server and
ultimately to your CGI Program. Most frequently browser uses two methods two pass this information to web server. These
methods are GET Method and POST Method.

Passing Information using GET method:


91

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY


The GET method sends the encoded user information appended to the page request. The page and the encoded information are
separated by the ? character as follows:

http://www.test.com/cgi-bin/hello.cgi?key1=value1&key2=value2
The GET method is the defualt method to pass information from browser to web server and it produces a long string that
appears in your browser's Location:box. Never use the GET method if you have password or other sensitive information to
pass to the server. The GET method has size limtation: only 1024 characters can be in a request string.
This information is passed using QUERY_STRING header and will be accessible in your CGI Program through
QUERY_STRING environment variable
You can pass information by simply concatenating key and value pairs alongwith any URL or you can use HTML <FORM>
tags to pass information using GET method.

Simple URL Example : Get Method


Here is a simple URL which will pass two values to hello_get.cgi program using GET method.
http://www.tutorialspoint.com/cgi-bin/hello_get.cgi?first_name=ZARA&last_name=ALI
Below is hello_get.cgi script to handle input given by web browser.

#!/usr/bin/perl
local ($buffer, @pairs, $pair, $name, $value, %FORM);
# Read in text
$ENV{'REQUEST_METHOD'} =~ tr/a-z/A-Z/;
if ($ENV{'REQUEST_METHOD'} eq "GET")
{
$buffer = $ENV{'QUERY_STRING'};
}
# Split information into name/value pairs
@pairs = split(/&/, $buffer);
foreach $pair (@pairs)
{
($name, $value) = split(/=/, $pair);
$value =~ tr/+/ /;
$value =~ s/%(..)/pack("C", hex($1))/eg;
$FORM{$name} = $value;
}
$first_name = $FORM{first_name};
$last_name = $FORM{last_name};
print
print
print
print
print
print
print
print
print

"Content-type:text/html\r\n\r\n";
"<html>";
"<head>";
"<title>Hello - Second CGI Program</title>";
"</head>";
"<body>";
"<h2>Hello $first_name $last_name - Second CGI Program</h2>";
"</body>";
"</html>";

1;

92

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY


Simple FORM Example: GET Method
Here is a simple example which passes two values using HTML FORM and submit button. We are going to use same CGI
script hello_get.cgi to handle this imput.

<FORM action="/cgi-bin/hello_get.cgi" method="GET">


First Name: <input type="text" name="first_name"> <br>
Last Name: <input type="text" name="last_name">
<input type="submit" value="Submit">
</FORM>
Here is the actual output of the above form, You enter First and Last Name and then click submit button to see the result.

First Name:

Last Name:

Submit

Passing Information using POST method:


A generally more reliable method of passing information to a CGI program is the POST method. This packages the
information in exactly the same way as GET methods, but instead of sending it as a text string after a ? in the URL it sends it
as a separate message. This message comes into the CGI script in the form of the standard input.
Below is hello_post.cgi script to handle input given by web browser. This script will handle GET as well as POST method.

#!/usr/bin/perl
local ($buffer, @pairs, $pair, $name, $value, %FORM);
# Read in text
$ENV{'REQUEST_METHOD'} =~ tr/a-z/A-Z/;
if ($ENV{'REQUEST_METHOD'} eq "POST")
{
read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'});
}else {
$buffer = $ENV{'QUERY_STRING'};
}
# Split information into name/value pairs
@pairs = split(/&/, $buffer);
foreach $pair (@pairs)
{
($name, $value) = split(/=/, $pair);
$value =~ tr/+/ /;
$value =~ s/%(..)/pack("C", hex($1))/eg;
$FORM{$name} = $value;
}
$first_name = $FORM{first_name};
$last_name = $FORM{last_name};
print "Content-type:text/html\r\n\r\n";
print "<html>";

93

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY


print
print
print
print
print
print
print

"<head>";
"<title>Hello - Second CGI Program</title>";
"</head>";
"<body>";
"<h2>Hello $first_name $last_name - Second CGI Program</h2>";
"</body>";
"</html>";

1;
Let us take again same examle as above, which passes two values using HTML FORM and submit button. We are going to use
CGI script hello_post.cgi to handle this imput.

<FORM action="/cgi-bin/hello_post.cgi" method="POST">


First Name: <input type="text" name="first_name"> <br>
Last Name: <input type="text" name="last_name">
<input type="submit" value="Submit">
</FORM>
Here is the actual output of the above form, You enter First and Last Name and then click submit button to see the result.

First Name:
Submit

Last Name:

Passing Checkbox Data to CGI Program


Checkboxes are used when more than one option is required to be selected.
Here is example HTML code for a form with two checkboxes

<form action="/cgi-bin/checkbox.cgi" method="POST" target="_blank">


<input type="checkbox" name="maths" value="on"> Maths
<input type="checkbox" name="physics" value="on"> Physics
<input type="submit" value="Select Subject">
</form>
The result of this code is the following form

Maths

Physics

Select Subject

Below is checkbox.cgi script to handle input given by web browser for radio button.

#!/usr/bin/perl

94

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY


local ($buffer, @pairs, $pair, $name, $value, %FORM);
# Read in text
$ENV{'REQUEST_METHOD'} =~ tr/a-z/A-Z/;
if ($ENV{'REQUEST_METHOD'} eq "POST")
{
read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'});
}else {
$buffer = $ENV{'QUERY_STRING'};
}
# Split information into name/value pairs
@pairs = split(/&/, $buffer);
foreach $pair (@pairs)
{
($name, $value) = split(/=/, $pair);
$value =~ tr/+/ /;
$value =~ s/%(..)/pack("C", hex($1))/eg;
$FORM{$name} = $value;
}
if( $FORM{maths} ){
$maths_flag ="ON";
}else{
$maths_flag ="OFF";
}
if( $FORM{physics} ){
$physics_flag ="ON";
}else{
$physics_flag ="OFF";
}
print
print
print
print
print
print
print
print
print
print

"Content-type:text/html\r\n\r\n";
"<html>";
"<head>";
"<title>Checkbox - Third CGI Program</title>";
"</head>";
"<body>";
"<h2> CheckBox Maths is : $maths_flag</h2>";
"<h2> CheckBox Physics is : $physics_flag</h2>";
"</body>";
"</html>";

1;

Passing Radio Button Data to CGI Program


Radio Buttons are used when only one option is required to be selected.
Here is example HTML code for a form with two radio button:

<form action="/cgi-bin/radiobutton.cgi" method="POST" target="_blank">


<input type="radio" name="subject" value="maths"> Maths
<input type="radio" name="subject" value="physics"> Physics
<input type="submit" value="Select Subject">
</form>
The result of this code is the following form

Maths

Physics

Select Subject

95

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY


Below is radiobutton.cgi script to handle input given by web browser for radio button.

#!/usr/bin/perl
local ($buffer, @pairs, $pair, $name, $value, %FORM);
# Read in text
$ENV{'REQUEST_METHOD'} =~ tr/a-z/A-Z/;
if ($ENV{'REQUEST_METHOD'} eq "POST")
{
read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'});
}else {
$buffer = $ENV{'QUERY_STRING'};
}
# Split information into name/value pairs
@pairs = split(/&/, $buffer);
foreach $pair (@pairs)
{
($name, $value) = split(/=/, $pair);
$value =~ tr/+/ /;
$value =~ s/%(..)/pack("C", hex($1))/eg;
$FORM{$name} = $value;
}
$subject = $FORM{subject};
print
print
print
print
print
print
print
print
print

"Content-type:text/html\r\n\r\n";
"<html>";
"<head>";
"<title>Radio - Fourth CGI Program</title>";
"</head>";
"<body>";
"<h2> Selected Subject is $subject</h2>";
"</body>";
"</html>";

1;

Passing Text Area Data to CGI Program


TEXTAREA element is used when multiline text has to be passed to the CGI Program.
Here is example HTML code for a form with a TEXTAREA box:

<form action="/cgi-bin/textarea.cgi" method="POST" target="_blank">


<textarea name="review" cols=40 rows=4>
Type your text here...
</textarea>
<input type="submit" value="Submit">
</form>
The result of this code is the following form

96

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

Submit

Below is textarea.cgi script to handle input given by web browser.

#!/usr/bin/perl
local ($buffer, @pairs, $pair, $name, $value, %FORM);
# Read in text
$ENV{'REQUEST_METHOD'} =~ tr/a-z/A-Z/;
if ($ENV{'REQUEST_METHOD'} eq "POST")
{
read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'});
}else {
$buffer = $ENV{'QUERY_STRING'};
}
# Split information into name/value pairs
@pairs = split(/&/, $buffer);
foreach $pair (@pairs)
{
($name, $value) = split(/=/, $pair);
$value =~ tr/+/ /;
$value =~ s/%(..)/pack("C", hex($1))/eg;
$FORM{$name} = $value;
}
$text_content = $FORM{textcontent};
print
print
print
print
print
print
print
print
print

"Content-type:text/html\r\n\r\n";
"<html>";
"<head>";
"<title>Text Area - Fifth CGI Program</title>";
"</head>";
"<body>";
"<h2> Entered Text Content is $text_content</h2>";
"</body>";
"</html>";

1;

Passing Drop Down Box Data to CGI Program


Drop Down Box is used when we have many options available but only one or two will be selected.
Here is example HTML code for a form with one drop down box

<form action="/cgi-bin/dropdown.cgi" method="POST" target="_blank">


<select name="dropdown">
<option value="Maths" selected>Maths<option>
<option value="Physics">Physics<option>
</select>
<input type="submit" value="Submit">
</form>
The result of this code is the following form

97

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY


Submit

Below is dropdown.cgi script to handle input given by web browser.

#!/usr/bin/perl
local ($buffer, @pairs, $pair, $name, $value, %FORM);
# Read in text
$ENV{'REQUEST_METHOD'} =~ tr/a-z/A-Z/;
if ($ENV{'REQUEST_METHOD'} eq "POST")
{
read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'});
}else {
$buffer = $ENV{'QUERY_STRING'};
}
# Split information into name/value pairs
@pairs = split(/&/, $buffer);
foreach $pair (@pairs)
{
($name, $value) = split(/=/, $pair);
$value =~ tr/+/ /;
$value =~ s/%(..)/pack("C", hex($1))/eg;
$FORM{$name} = $value;
}
$subject = $FORM{dropdown};
print
print
print
print
print
print
print
print
print

"Content-type:text/html\r\n\r\n";
"<html>";
"<head>";
"<title>Dropdown Box - Sixth CGI Program</title>";
"</head>";
"<body>";
"<h2> Selected Subject is $subject</h2>";
"</body>";
"</html>";

1;

Using Cookies in CGI


HTTP protocol is a stateless protocol. But for a commercial website it is required to maintain session information among
different pages. For example one user regitration ends after completing many pages. But how to maintain user's session
information across all the web pages.
In many situations, using cookies is the most efficient method of remembering and tracking preferences, purchases,
commissions, and other information required for better visitor experience or site statistics.

How It Works
Your server sends some data to the visitor's browser in the form of a cookie. The browser may accept the cookie. If it does, it
is stored as a plain text record on the visitor's hard drive. Now, when the visitor arrives at another page on your site, the cookie
is available for retrieval. Once retrieved, your server knows/remembers what was stored.
Cookies are a plain text data record of 5 variable-length fields:

Expires : The date the cookie will expire. If this is blank, the cookie will expire when the visitor quits the browser.
Domain : The domain name of your site.

98

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY


Path : The path to the directory or web page that set the cookie. This may be blank if you want to retrieve the
cookie from any directory or page.

Secure : If this field contains the word "secure" then the cookie may only be retrieved with a secure server. If this
field is blank, no such restriction exists.

Name=Value : Cookies are set and retrviewed in the form of key and value pairs.
Setting up Cookies
This is very easy to send cookies to browser. These cookies will be sent along with HTTP Header. Assuming you want to set
UserID and Password as cookies. So it will be done as follows

#!/usr/bin/perl
print "Set-Cookie:UserID=XYZ;\n";
print "Set-Cookie:Password=XYZ123;\n";
print "Set-Cookie:Expires=Tuesday, 31-Dec-2007 23:12:40 GMT";\n";
print "Set-Cookie:Domain=www.tutorialspoint.com;\n";
print "Set-Cookie:Path=/perl;\n";
print "Content-type:text/html\r\n\r\n";
...........Rest of the HTML Content....
From this example you must have understood how to set cookies. We use Set-Cookie HTTP header to set cookies.
Here it is optional to set cookies attributes like Expires, Domain, and Path. It is notable that cookies are set before sending
magic line "Content-type:text/html\r\n\r\n.

Retrieving Cookies
This is very easy to retrieve all the set cookies. Cookies are stored in CGI environment variable HTTP_COOKIE and they will
have following form.

key1=value1;key2=value2;key3=value3....
Here is an example of how to retrieving cookies.

#!/usr/bin/perl
$rcvd_cookies = $ENV{'HTTP_COOKIE'};
@cookies = split /;/, $rcvd_cookies;
foreach $cookie ( @cookies ){
($key, $val) = split(/=/, $cookie); # splits on the first =.
$key =~ s/^\s+//;
$val =~ s/^\s+//;
$key =~ s/\s+$//;
$val =~ s/\s+$//;
if( $key eq "UserID" ){
$user_id = $val;
}elsif($key eq "Password"){
$password = $val;
}
}
print "User ID = $user_id\n";
print "Password = $password\n";
This will produce following result

99

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY


User ID = XYZ
Password = XYZ123

Unit IV

Introduction to ASP
An ASP file can contain text, HTML tags and scripts. Scripts in an ASP file are executed
on the server

What you should already know


Before you continue you should have some basic understanding of the following:

HTML / XHTML
A scripting language like JavaScript or VBScript

What is ASP?
ASP stands for Active Server Pages
ASP is a program that runs inside IIS
IIS stands for Internet Information Services
IIS comes as a free component with Windows 2000
IIS is also a part of the Windows NT 4.0 Option Pack
The Option Pack can be downloaded from Microsoft
PWS is a smaller - but fully functional - version of IIS
PWS can be found on your Windows 95/98 CD

ASP Compatibility
ASP is a Microsoft Technology
To run IIS you must have Windows NT 4.0 or later

100

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

To run PWS you must have Windows 95 or later


ChiliASP is a technology that runs ASP without Windows OS
InstantASP is another technology that runs ASP without Windows

What is an ASP File?


An ASP file is just the same as an HTML file
An ASP file can contain text, HTML, XML, and scripts
Scripts in an ASP file are executed on the server
An ASP file has the file extension ".asp"

How Does ASP Differ from HTML?


When a browser requests an HTML file, the server returns the file
When a browser requests an ASP file, IIS passes the request to the ASP engine.
The ASP engine reads the ASP file, line by line, and executes the scripts in the
file. Finally, the ASP file is returned to the browser as plain HTML

What can ASP do for you?


Dynamically edit, change or add any content of a Web page
Respond to user queries or data submitted from HTML forms
Access any data or databases and return the results to a browser
Customize a Web page to make it more useful for individual users
The advantages of using ASP instead of CGI and Perl, are those of simplicity and
speed

Provide security since your ASP code can not be viewed from the browser
Clever ASP programming can minimize the network traffic

ASP Syntax
You cannot view the ASP source code by selecting "View source" in a browser, you will
only see the output from the ASP file, which is plain HTML. This is because the scripts
are executed on the server before the result is sent back to the browser.
In our ASP tutorial, every example displays the hidden ASP source code. This will make
it easier for you to understand how it works.

101

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

The Basic Syntax Rule


An ASP file normally contains HTML tags, just like an HTML file. However, an ASP file
can also contain server scripts, surrounded by the delimiters <% and %>. Server scripts
are executed on the server, and can contain any expressions, statements, procedures, or
operators valid for the scripting language you prefer to use.

Write Output to a Browser


The response.write command is used to write output to a browser. The following example
sends the text "Hello World" to the browser:
<html>
<body>
<%
response.write("Hello World!")
%>
</body>
</html>

There is also a shorthand method for the response.write command. The following
example also sends the text "Hello World" to the browser:
<html>
<body>
<%="Hello World!"%>
</body>
</html>

VBScript: You can use several scripting languages in ASP. However, the default
scripting language is VBScript:
<html>
<body>
<%
response.write("Hello World!")
%>
</body>
</html>

The example above writes "Hello World!" into the body of the document.

JavaScript
To set JavaScript as the default scripting language for a particular page you must insert a
language specification at the top of the page:
<%@ language="javascript"%>
<html>
<body>
<%
Response.Write("Hello World!")
%>
</body>
</html>

Note: Unlike VBScript - JavaScript is case sensitive. You will have to write your ASP
code with uppercase letters and lowercase letters when the language requires it.

102

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

Examples
Write text with ASP
How to write some text with ASP.
<html>
<body>
<%
response.write("Hello World!")
%>
</body>
</html>

Add some HTML to the text


How to format the text with HTML tags.
<html>
<body>
<%
response.write("<h2>You can use HTML tags to format the text!</h2>")
%>
<%
response.write("<p style='color:#0000ff'>This text is styled with the style attribute!
</p>")
%>
</body>
</html>

Output Result:

You can use HTML tags to format the text!


This text is styled with the style attribute!

Other Scripting Languages


ASP is shipped with VBScript and JScript (Microsoft's implementation of JavaScript). If
you want to script in another language, like PERL, REXX, or Python, you will have to
install script engines for them.

ASP Variables
A variable is used to store information.
If the variable is declared outside a procedure it can be changed by any script in the ASP
file. If the variable is declared inside a procedure, it is created and destroyed every time
the procedure is executed.

Lifetime of Variables
A variable declared outside a procedure can be accessed and changed by any script in the
ASP file.
A variable declared inside a procedure is created and destroyed every time the procedure
is executed. No scripts outside the procedure can access or change the variable.
103

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

To declare variables accessible to more than one ASP file, declare them as session
variables or application variables.

Session Variables
Session variables are used to store information about ONE single user, and are available
to all pages in one application. Typically information stored in session variables are
name, id, and preferences.

Application Variables
Application variables are also available to all pages in one application. Application
variables are used to store information about ALL users in a specific application.

Examples
Declare a variable
Variables are used to store information. This example demonstrates how to declare a
variable, assign a value to it, and use the value in a text.
<html>
<body>
<%
dim name
name="Senthil"
response.write("My name is: " & name)
%>
</body>
</html>
Output Result:

My name is: Senthil


Declare an array
Arrays are used to store a series of related data items. This example demonstrates how to
declare an array that stores names.
<html>
<body>
<%
Dim famname(5),i
famname(0) = "Senthil"
famname(1) = "kumar"
famname(2) = "vin"
famname(3) = "bala"
famname(4) = "ramu
famname(5) = "vijay"
For i = 0 to 5

104

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY


response.write(famname(i) & "<br />")
Next
%>
</body>
</html>
Output Result:
Senthil
kumar
vin
bala
ramu
vijay

Loop through the HTML headers


How to loop through the six headers in HTML.
<html>
<body>
<%
dim i
for i=1 to 6
response.write("<h" & i & ">Header " & i & "</h" & i & ">")
next
%>
</body>
</html>
Output Result:

Header 1
Header 2
Header 3
Header 4
Header 5
Header 6

Time-based greeting using VBScript


This example will display a different message to the user depending on the time on the
server.
<html>
<body>
<%
dim h
h=hour(now())
response.write("<p>" & now())

105

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY


response.write(" (Norwegian Time) </p>")
If h<12 then
response.write("Good Morning!")
else
response.write("Good day!")
end if
%>
</body>
</html>
Output Result:

9/6/2007 5:58:28 AM (Norwegian Time)


Good Morning
Time-based greeting using JavaScript
This example is the same as the one above, but the syntax is different.
<%@ language="javascript" %>
<html>
<body>
<%
var d=new Date()
var h=d.getHours()
Response.Write("<p>")
Response.Write(d + " (Norwegian Time)")
Response.Write("</p>")
if (h<12)
{
Response.Write("Good Morning!")
}
else
{
Response.Write("Good day!")
}
%>
</body>
</html>

Output Result:
Thu Sep 6 05:59:12 EDT 2007 (Norwegian Time)
Good Morning!

ASP Procedures
In ASP you can call a JavaScript procedure from a VBScript and vice versa.

Procedures
The ASP source code can contain procedures and functions:
<html>
<head>
<%
sub vbproc(num1,num2)
response.write(num1*num2)
end sub

106

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY


%>
</head>
<body>
<p>Result: <%call vbproc(3,4)%></p>
</body>
</html>

Insert the <%@ language="language" %> line above the <html> tag to write procedures
or functions in another scripting language than default:
<%@ language="javascript" %>
<html>
<head>
<%
function jsproc(num1,num2)
{
Response.Write(num1*num2)
}
%>
</head>
<body>
<p>Result: <%jsproc(3,4)%></p>
</body>
</html>

Differences Between VBScript and JavaScript


When calling a VBScript or a JavaScript procedure from an ASP file written in VBScript,
you can use the "call" keyword followed by the procedure name. If a procedure requires
parameters, the parameter list must be enclosed in parentheses when using the "call"
keyword. If you omit the "call" keyword, the parameter list must not be enclosed in
parentheses. If the procedure has no parameters, the parentheses are optional.
When calling a JavaScript or a VBScript procedure from an ASP file written in
JavaScript, always use parentheses after the procedure name.

Examples
Call a procedure using VBScript
How to call a VBScript procedure from ASP.
<html>
<head>
<%
sub vbproc(num1,num2)
response.write(num1*num2)
end sub
%>
</head>
<body>
<p>
You can call a procedure like this:
</p>
<p>
Result: <%call vbproc(3,4)%>
</p>

107

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY


<p>
Or, like this:
</p>
<p>
Result: <%vbproc 3,4%>
</p>
</body>
</html>
Output Result:

Result: 12
Or, like this:
Result: 12
Call a procedure using JavaScript
How to call a JavaScript procedure from ASP.
<%@ language="javascript" %>
<html>
<head>
<%
function jsproc(num1,num2)
{
Response.Write(num1*num2)
}
%>
</head>
<body>
<p>
Result: <%jsproc(3,4)%>
</p>
</body>
</html>
Output Result:

Result: 12
Call procedures using VBScript
How to call both a JavaScript procedure and a VBScript procedure in an ASP file.
<html>
<head>
<%
sub vbproc(num1,num2)
Response.Write(num1*num2)
end sub
%>
<script language="javascript" runat="server">
function jsproc(num1,num2)
{
Response.Write(num1*num2)
}
</script>

108

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY


</head>
<body>
<p>Result: <%call vbproc(3,4)%></p>
<p>Result: <%call jsproc(3,4)%></p>
</body>
</html>

Output Result:
Result: 12
Result: 12

ASP Forms and User Input


The Request.QueryString and Request.Form commands may be used to retrieve
information from forms, like user input.

User Input
The Request object may be used to retrieve user information from forms.
Form example:
<form method="get" action="simpleform.asp">
First Name: <input type="text" name="fname" />
<br />
Last Name: <input type="text" name="lname" />
<br /><br />
<input type="submit" value="Submit" />
</form>

User input can be retrieved in two ways: With Request.QueryString or Request.Form.

Request.QueryString
The Request.QueryString command is used to collect values in a form with
method="get". Information sent from a form with the GET method is visible to everyone
(it will be displayed in the browser's address bar) and has limits on the amount of
information to send.
If a user typed "Bill" and "Gates" in the form example above, the URL sent to the server
would look like this:
http://www.w3schools.com/simpleform.asp?fname=Bill&lname=Gates

Assume that the ASP file "simpleform.asp" contains the following script:
<body>
Welcome
<%
response.write(request.querystring("fname"))
response.write(" " & request.querystring("lname"))
%>
</body>

The browser will display the following in the body of the document:

109

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY


Welcome Bill Gates

Request.Form
The Request.Form command is used to collect values in a form with method="post".
Information sent from a form with the POST method is invisible to others and has no
limits on the amount of information to send.
If a user typed "Bill" and "Gates" in the form example above, the URL sent to the server
would look like this:
http://www.w3schools.com/simpleform.asp

Assume that the ASP file "simpleform.asp" contains the following script:
<body>
Welcome
<%
response.write(request.form("fname"))
response.write(" " & request.form("lname"))
%>
</body>

The browser will display the following in the body of the document:
Welcome Bill Gates

Form Validation
User input should be validated on the browser whenever possible (by client scripts).
Browser validation is faster and you reduce the server load.
You should consider using server validation if the user input will be inserted into a
database. A good way to validate a form on the server is to post the form to itself, instead
of jumping to a different page. The user will then get the error messages on the same
page as the form. This makes it easier to discover the error.

Examples
A form with method="get"
How to interact with the user, with the Request.QueryString command.
<html>
<body>
<form action="demo_reqquery.asp" method="get">
Your name: <input type="text" name="fname" size="20" />
<input type="submit" value="Submit" />
</form>
<%
dim fname
fname=Request.QueryString("fname")
If fname<>"" Then
Response.Write("Hello " & fname & "!<br />")
Response.Write("How are you today?")
End If
%>
</body>
</html>

110

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

A form with method="post"


How to interact with the user, with the Request.Form command.
<html>
<body>
<form action="demo_simpleform.asp" method="post">
Your name: <input type="text" name="fname" size="20" />
<input type="submit" value="Submit" />
</form>
<%
dim fname
fname=Request.Form("fname")
If fname<>"" Then
Response.Write("Hello " & fname & "!<br />")
Response.Write("How are you today?")
End If
%>
</body>
</html>

A form with radio buttons


How to interact with the user, through radio buttons, with the Request.Form command.
<html>
<%
dim cars
cars=Request.Form("cars")
%>
<body>
<form action="demo_radiob.asp" method="post">
<p>Please select your favorite car:</p>
<input type="radio" name="cars"
<%if cars="Volvo" then Response.Write("checked")%>
value="Volvo">Volvo</input>
<br />
<input type="radio" name="cars"
<%if cars="Saab" then Response.Write("checked")%>
value="Saab">Saab</input>
<br />
<input type="radio" name="cars"
<%if cars="BMW" then Response.Write("checked")%>
value="BMW">BMW</input>
<br /><br />
<input type="submit" value="Submit" />
</form>
<%
if cars<>"" then
Response.Write("<p>Your favorite car is: " & cars & "</p>")
end if
%>
</body>
</html>

ASP Cookies
111

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

A cookie is often used to identify a user.

What is a Cookie?
A cookie is often used to identify a user. A cookie is a small file that the server embeds on
the user's computer. Each time the same computer requests a page with a browser, it will
send the cookie too. With ASP, you can both create and retrieve cookie values.

How to Create a Cookie?


The "Response.Cookies" command is used to create cookies.
Note: The Response.Cookies command must appear BEFORE the <html> tag.
In the example below, we will create a cookie named "firstname" and assign the value
"Alex" to it:
<%
Response.Cookies("firstname")="Alex"
%>

It is also possible to assign properties to a cookie, like setting a date when the cookie
should expire:
<%
Response.Cookies("firstname")="Alex"
Response.Cookies("firstname").Expires=#May 10,2002#
%>

How to Retrieve a Cookie Value?


The "Request.Cookies" command is used to retrieve a cookie value.
In the example below, we retrieve the value of the cookie named "firstname" and display
it on a page:
<%
fname=Request.Cookies("firstname")
response.write("Firstname=" & fname)
%>

Output:
Firstname=Alex

A Cookie with Keys


If a cookie contains a collection of multiple values, we say that the cookie has Keys.
In the example below, we will create a cookie collection named "user". The "user" cookie
has Keys that contains information about a user:
<%
Response.Cookies("user")("firstname")="John"
Response.Cookies("user")("lastname")="Smith"

112

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY


Response.Cookies("user")("country")="Norway"
Response.Cookies("user")("age")="25"
%>

Read all Cookies


Look at the following code:
<%
Response.Cookies("firstname")="Alex"
Response.Cookies("user")("firstname")="John"
Response.Cookies("user")("lastname")="Smith"
Response.Cookies("user")("country")="Norway"
Response.Cookies("user")("age")="25"
%>

Assume that your server has sent all the cookies above to a user.
Now we want to read all the cookies sent to a user. The example below shows how to do
it (note that the code below checks if a cookie has Keys with the HasKeys property):
<html>
<body>
<%
dim x,y
for each x in Request.Cookies
response.write("<p>")
if Request.Cookies(x).HasKeys then
for each y in Request.Cookies(x)
response.write(x & ":" & y & "=" & Request.Cookies(x)(y))
response.write("<br />")
next
else
Response.Write(x & "=" & Request.Cookies(x) & "<br />")
end if
response.write "</p>"
next
%>
</body>
</html>

Output:
firstname=Alex
user:firstname=John
user:lastname=Smith
user:country=Norway
user:age=25

What if a Browser Does NOT Support Cookies?


If your application deals with browsers that do not support cookies, you will have to use
other methods to pass information from one page to another in your application. There
are two ways of doing this:

113

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

1. Add parameters to a URL


You can add parameters to a URL:
<a href="welcome.asp?fname=John&lname=Smith">
Go to Welcome Page</a>

And retrieve the values in the "welcome.asp" file like this:


<%
fname=Request.querystring("fname")
lname=Request.querystring("lname")
response.write("<p>Hello " & fname & " " & lname & "!</p>")
response.write("<p>Welcome to my Web site!</p>")
%>

2. Use a form
You can use a form. The form passes the user input to "welcome.asp" when the user
clicks on the Submit button:

<form method="post" action="welcome.asp">


First Name: <input type="text" name="fname" value="">
Last Name: <input type="text" name="lname" value="">
<input type="submit" value="Submit">
</form>

Retrieve the values in the "welcome.asp" file like this:


<%
fname=Request.form("fname")
lname=Request.form("lname")
response.write("<p>Hello " & fname & " " & lname & "!</p>")
response.write("<p>Welcome to my Web site!</p>")
%>

Examples
Welcome cookie
How to create a Welcome cookie.
<%
dim numvisits
response.cookies("NumVisits").Expires=date+365
numvisits=request.cookies("NumVisits")
if numvisits="" then
response.cookies("NumVisits")=1
response.write("Welcome! This is the first time you are visiting this Web page.")
else
response.cookies("NumVisits")=numvisits+1
response.write("You have visited this ")
response.write("Web page " & numvisits)
if numvisits=1 then
response.write " time before!"
else
response.write " times before!"
end if

114

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY


end if
%>
<html>
<body>
</body>
</html>

Welcome! This is the first time you are visiting this Web page.

ASP Session Object


The Session object is used to store information about, or change settings for a user
session. Variables stored in the Session object hold information about one single user, and
are available to all pages in one application.

The Session object


When you are working with an application, you open it, do some changes and then you
close it. This is much like a Session. The computer knows who you are. It knows when
you start the application and when you end. But on the internet there is one problem: the
web server does not know who you are and what you do because the HTTP address
doesn't maintain state.
ASP solves this problem by creating a unique cookie for each user. The cookie is sent to
the client and it contains information that identifies the user. This interface is called the
Session object.
The Session object is used to store information about, or change settings for a user
session. Variables stored in the Session object hold information about one single user, and
are available to all pages in one application. Common information stored in session
variables are name, id, and preferences. The server creates a new Session object for each
new user, and destroys the Session object when the session expires.

When does a Session Start?


A session starts when:

A new user requests an ASP file, and the Global.asa file includes a
Session_OnStart procedure

A value is stored in a Session variable

A user requests an ASP file, and the Global.asa file uses the <object> tag to
instantiate an object with session scope

When does a Session End?


A session ends if a user has not requested or refreshed a page in the application for a
specified period. By default, this is 20 minutes.
If you want to set a timeout interval that is shorter or longer than the default, you can set
the Timeout property.
The example below sets a timeout interval of 5 minutes:
<%

115

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY


Session.Timeout=5
%>

To end a session immediately, you may use the Abandon method:


<%
Session.Abandon
%>

Note: The main problem with sessions is WHEN they should end. We do not know if the
user's last request was the final one or not. So we do not know how long we should keep
the session "alive". Waiting too long for an idle session uses up resources on the server,
but if the session is deleted too soon the user has to start all over again because the server
has deleted all the information. Finding the right timeout interval can be difficult!
Tip: If you are using session variables, store SMALL amounts of data in them.

Store and Retrieve Session Variables


The most important thing about the Session object is that you can store variables in it.
The example below will set the Session variable username to "Donald Duck" and the
Session variable age to "50":
<%
Session("username")="Donald Duck"
Session("age")=50
%>

When the value is stored in a session variable it can be reached from ANY page in the
ASP application:
Welcome <%Response.Write(Session("username"))%>

The line above returns: "Welcome Donald Duck".


You can also store user preferences in the Session object, and then access that preference
to choose what page to return to the user.
The example below specifies a text-only version of the page if the user has a low screen
resolution:
<%If Session("screenres")="low" Then%>
This is the text version of the page
<%Else%>
This is the multimedia version of the page
<%End If%>

Remove Session Variables


The Contents collection contains all session variables.
It is possible to remove a session variable with the Remove method.
The example below removes the session variable "sale" if the value of the session
variable "age" is lower than 18:
<%
If Session.Contents("age")<18 then
Session.Contents.Remove("sale")
End If
%>

116

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

To remove all variables in a session, use the RemoveAll method:


<%
Session.Contents.RemoveAll()
%>

Loop Through the Contents Collection


The Contents collection contains all session variables. You can loop through the Contents
collection, to see what's stored in it:
<%
Session("username")="Donald Duck"
Session("age")=50
dim i
For Each i in Session.Contents
Response.Write(i & "<br />")
Next
%>

Result:
username
age

If you do not know the number of items in the Contents collection, you can use the Count
property:
<%
dim i
dim j
j=Session.Contents.Count
Response.Write("Session variables: " & j)
For i=1 to j
Response.Write(Session.Contents(i) & "<br />")
Next
%>

Result:
Session variables: 2
Donald Duck
50

Loop Through the StaticObjects Collection


You can loop through the StaticObjects collection, to see the values of all objects stored
in the Session object:
<%
dim i
For Each i in Session.StaticObjects
Response.Write(i & "<br />")
Next
%>

ASP Application Object


A group of ASP files that work together to perform some purpose is called an application.
117

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

The Application object in ASP is used to tie these files together.

Application Object
An application on the Web may be a group of ASP files. The ASP files work together to
perform some purpose. The Application object in ASP is used to tie these files together.
The Application object is used to store and access variables from any page, just like the
Session object. The difference is that ALL users share one Application object, while with
Sessions there is one Session object for EACH user.
The Application object should hold information that will be used by many pages in the
application (like database connection information). This means that you can access the
information from any page. It also means that you can change the information in one
place and the changes will automatically be reflected on all pages.

Store and Retrieve Application Variables


Application variables can be accessed and changed by any page in the application.
You can create Application variables in "Global.asa" like this:
<script language="vbscript" runat="server">
Sub Application_OnStart
application("vartime")=""
application("users")=1
End Sub
</script>

In the example above we have created two Application variables: "vartime" and "users".
You can access the value of an Application variable like this:
There are
<%
Response.Write(Application("users"))
%>
active connections.

Loop Through the Contents Collection


The Contents collection contains all application variables. You can loop through the
Contents collection, to see what's stored in it:
<%
dim i
For Each i in Application.Contents
Response.Write(i & "<br />")
Next
%>

If you do not know the number of items in the Contents collection, you can use the Count
property:
<%
dim i
dim j
j=Application.Contents.Count
For i=1 to j

118

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY


Response.Write(Application.Contents(i) & "<br />")
Next
%>

Loop Through the StaticObjects Collection


You can loop through the StaticObjects collection, to see the values of all objects stored
in the Application object:
<%
dim i
For Each i in Application.StaticObjects
Response.Write(i & "<br />")
Next
%>

Lock and Unlock


You can lock an application with the "Lock" method. When an application is locked, the
users cannot change the Application variables (other than the one currently accessing it).
You can unlock an application with the "Unlock" method. This method removes the lock
from the Application variable:
<%
Application.Lock
'do some application object operations
Application.Unlock
%>

ASP The Global.asa file


The Global.asa file is an optional file that can contain declarations of objects, variables,
and methods that can be accessed by every page in an ASP application.

The Global.asa file


The Global.asa file is an optional file that can contain declarations of objects, variables,
and methods that can be accessed by every page in an ASP application. All valid browser
scripts (JavaScript, VBScript, JScript, PerlScript, etc.) can be used within Global.asa.
The Global.asa file can contain only the following:

Application events

Session events

<object> declarations

TypeLibrary declarations

the #include directive


119

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

Note: The Global.asa file must be stored in the root directory of the ASP application, and
each application can only have one Global.asa file.

Events in Global.asa
In Global.asa you can tell the application and session objects what to do when the
application/session starts and what to do when the application/session ends. The code for
this is placed in event handlers. The Global.asa file can contain four types of events:
Application_OnStart - This event occurs when the FIRST user calls the first page from
an ASP application. This event occurs after the Web server is restarted or after the
Global.asa file is edited. The "Session_OnStart" event occurs immediately after this
event.
Session_OnStart - This event occurs EVERY time a NEW user requests his or her first
page in the ASP application.
Session_OnEnd - This event occurs EVERY time a user ends a session. A user ends a
session after a page has not been requested by the user for a specified time (by default
this is 20 minutes).
Application_OnEnd - This event occurs after the LAST user has ended the session.
Typically, this event occurs when a Web server stops. This procedure is used to clean up
settings after the Application stops, like delete records or write information to text files.
A Global.asa file could look something like this:
<script language="vbscript" runat="server">
sub Application_OnStart
'some code
end sub
sub Application_OnEnd
'some code
end sub
sub Session_OnStart
'some code
end sub
sub Session_OnEnd
'some code
end sub
</script>

Note: Because we cannot use the ASP script delimiters (<% and %>) to insert scripts in
the Global.asa file, we put subroutines inside an HTML <script> element.

<object> Declarations
It is possible to create objects with session or application scope in Global.asa by using the
<object> tag.
Note: The <object> tag should be outside the <script> tag!

Syntax
<object runat="server" scope="scope" id="id"
{progid="progID"|classid="classID"}>
....
</object>

120

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

Parameter

Description

scope

Sets the scope of the object (either Session or Application)

id

Specifies a unique id for the object

ProgID

An id associated with a class id. The format for ProgID is


[Vendor.]Component[.Version]
Either ProgID or ClassID must be specified.

ClassID

Specifies a unique id for a COM class object.


Either ProgID or ClassID must be specified.

Examples
The first example creates an object of session scope named "MyAd" by using the ProgID
parameter:
<object runat="server" scope="session" id="MyAd"
progid="MSWC.AdRotator">
</object>

The second example creates an object of application scope named "MyConnection" by


using the ClassID parameter:
<object runat="server" scope="application" id="MyConnection"
classid="Clsid:8AD3067A-B3FC-11CF-A560-00A0C9081C21">
</object>

The objects declared in the Global.asa file can be used by any script in the application:
GLOBAL.ASA:
<object runat="server" scope="session" id="MyAd"
progid="MSWC.AdRotator">
</object>

You could reference the object "MyAd" from any page in the ASP application:
SOME .ASP FILE:
<%=MyAd.GetAdvertisement("/banners/adrot.txt")%>

TypeLibrary Declarations
A TypeLibrary is a container for the contents of a DLL file corresponding to a COM
object. By including a call to the TypeLibrary in the Global.asa file, the constants of the
COM object can be accessed, and errors can be better reported by the ASP code. If your
Web application relies on COM objects that have declared data types in type libraries,
you can declare the type libraries in Global.asa.

Syntax
<!--METADATA TYPE="TypeLib"
file="filename"
uuid="typelibraryuuid"
version="versionnumber"
lcid="localeid"

121

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY


-->

Parameter
file

Description
Specifies an absolute path to a type library.
Either the file parameter or the uuid parameter is required

uuid

Specifies a unique identifier for the type library.


Either the file parameter or the uuid parameter is required

version

Optional. Used for selecting version. If the requested version is not found,
then the most recent version is used

lcid

Optional. The locale identifier to be used for the type library

Error Values
The server can return one of the following error messages:
Error Code

Description

ASP 0222

Invalid type library specification

ASP 0223

Type library not found

ASP 0224

Type library cannot be loaded

ASP 0225

Type library cannot be wrapped

Note: METADATA tags can appear anywhere in the Global.asa file (both inside and
outside <script> tags). However, it is recommended that METADATA tags appear near
the top of the Global.asa file.

Restrictions
Restrictions on what you can include in the Global.asa file:

You can not display text that is written in the Global.asa file. This file can't
display information

You can only use Server and Application objects in the Application_OnStart and
Application_OnEnd subroutines. In the Session_OnEnd subroutine, you can use
Server, Application, and Session objects. In the Session_OnStart subroutine you
can use any built-in object

122

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

How to use the Subroutines


Global.asa is often used to initialize variables.
The example below shows how to detect the exact time a visitor first arrives on a Web
site. The time is stored in a Session variable named "started", and the value of the
"started" variable can be accessed from any ASP page in the application:
<script language="vbscript" runat="server">
sub Session_OnStart
Session("started")=now()
end sub
</script>

Global.asa can also be used to control page access.


The example below shows how to redirect every new visitor to another page, in this case
to a page called "newpage.asp":
<script language="vbscript" runat="server">
sub Session_OnStart
Response.Redirect("newpage.asp")
end sub
</script>

And you can include functions in the Global.asa file.


In the example below the Application_OnStart subroutine occurs when the Web server
starts. Then the Application_OnStart subroutine calls another subroutine named
"getcustomers". The "getcustomers" subroutine opens a database and retrieves a record
set from the "customers" table. The record set is assigned to an array, where it can be
accessed from any ASP page without querying the database:
<script language="vbscript" runat="server">
sub Application_OnStart
getcustomers
end sub
sub getcustomers
set conn=Server.CreateObject("ADODB.Connection")
conn.Provider="Microsoft.Jet.OLEDB.4.0"
conn.Open "c:/webdata/northwind.mdb"
set rs=conn.execute("select name from customers")
Application("customers")=rs.GetRows
rs.Close
conn.Close
end sub
</script>

Global.asa Example
In this example we will create a Global.asa file that counts the number of current visitors.

The Application_OnStart sets the Application variable "visitors" to 0 when the


server starts

The Session_OnStart subroutine adds one to the variable "visitors" every time a
new visitor arrives

The Session_OnEnd subroutine subtracts one from "visitors" each time this
subroutine is triggered
123

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

The Global.asa file:


<script language="vbscript" runat="server">
Sub Application_OnStart
Application("visitors")=0
End Sub
Sub Session_OnStart
Application.Lock
Application("visitors")=Application("visitors")+1
Application.UnLock
End Sub
Sub Session_OnEnd
Application.Lock
Application("visitors")=Application("visitors")-1
Application.UnLock
End Sub
</script>

To display the number of current visitors in an ASP file:


<html>
<head>
</head>
<body>
<p>
There are <%response.write(Application("visitors"))%>
online now!
</p>
</body>
</html>

ASP Sending e-mail with CDOSYS


CDOSYS is a built-in component in ASP. This component is used to send e-mails with
ASP.

Sending e-mail with CDOSYS


CDO (Collaboration Data Objects) is a Microsoft technology that is designed to simplify
the creation of messaging applications.
CDOSYS is a built-in component in ASP. We will show you how to use this component
to send e-mail with ASP.

How about CDONTs?


Microsoft has discontinued the use of CDONTs on Windows 2000, Windows XP and
Windows 2003. If you have used CDONTs in your ASP applications, you should update
the code and use the new CDO technology.

Examples using CDOSYS


Sending a text e-mail:
<%
Set myMail=CreateObject("CDO.Message")
myMail.Subject="Sending email with CDO"
myMail.From="mymail@mydomain.com"
myMail.To="someone@somedomain.com"

124

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY


myMail.TextBody="This is a message."
myMail.Send
set myMail=nothing
%>

Sending a text e-mail with Bcc and CC fields:


<%
Set myMail=CreateObject("CDO.Message")
myMail.Subject="Sending email with CDO"
myMail.From="mymail@mydomain.com"
myMail.To="someone@somedomain.com"
myMail.Bcc="someoneelse@somedomain.com"
myMail.Cc="someoneelse2@somedomain.com"
myMail.TextBody="This is a message."
myMail.Send
set myMail=nothing
%>

Sending an HTML e-mail:


<%
Set myMail=CreateObject("CDO.Message")
myMail.Subject="Sending email with CDO"
myMail.From="mymail@mydomain.com"
myMail.To="someone@somedomain.com"
myMail.HTMLBody = "<h1>This is a message.</h1>"
myMail.Send
set myMail=nothing
%>

Sending an HTML e-mail that sends a webpage from a website:


<%
Set myMail=CreateObject("CDO.Message")
myMail.Subject="Sending email with CDO"
myMail.From="mymail@mydomain.com"
myMail.To="someone@somedomain.com"
myMail.CreateMHTMLBody "http://www.w3schools.com/asp/"
myMail.Send
set myMail=nothing
%>

Sending an HTML e-mail that sends a webpage from a file on your computer:
<%
Set myMail=CreateObject("CDO.Message")
myMail.Subject="Sending email with CDO"
myMail.From="mymail@mydomain.com"
myMail.To="someone@somedomain.com"
myMail.CreateMHTMLBody "file://c:/mydocuments/test.htm"
myMail.Send
set myMail=nothing

125

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY


%>

Sending a text e-mail with an Attachment:


<%
Set myMail=CreateObject("CDO.Message")
myMail.Subject="Sending email with CDO"
myMail.From="mymail@mydomain.com"
myMail.To="someone@somedomain.com"
myMail.TextBody="This is a message."
myMail.AddAttachment "c:\mydocuments\test.txt"
myMail.Send
set myMail=nothing
%>

Sending a text e-mail using a remote server:


<%
Set myMail=CreateObject("CDO.Message")
myMail.Subject="Sending email with CDO"
myMail.From="mymail@mydomain.com"
myMail.To="someone@somedomain.com"
myMail.TextBody="This is a message."
myMail.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/sendusing")=2
'Name or IP of remote SMTP server
myMail.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpserver") _
="smtp.server.com"
'Server port
myMail.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpserverport") _
=25
myMail.Configuration.Fields.Update
myMail.Send
set myMail=nothing
%>

ASP Response Object


The ASP Response object is used to send output to the user from the server.

Response Object
The ASP Response object is used to send output to the user from the server. Its
collections, properties, and methods are described below:

Collections
Collection
Cookies

Description
Sets a cookie value. If the cookie does not exist, it will be created, and
take the value that is specified

Properties
Property

Description

126

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

Buffer

Specifies whether to buffer the page output or not

CacheControl

Sets whether a proxy server can cache the output generated by ASP or
not

Charset

Appends the name of a character-set to the content-type header in the


Response object

ContentType

Sets the HTTP content type for the Response object

Expires

Sets how long (in minutes) a page will be cached on a browser before it
expires

ExpiresAbsolute

Sets a date and time when a page cached on a browser will expire

IsClientConnected

Indicates if the client has disconnected from the server

Pics

Appends a value to the PICS label response header

Status

Specifies the value of the status line returned by the server

Methods
Method

Description

AddHeader

Adds a new HTTP header and a value to the HTTP response

AppendToLog

Adds a string to the end of the server log entry

BinaryWrite

Writes data directly to the output without any character conversion

Clear

Clears any buffered HTML output

End

Stops processing a script, and returns the current result

Flush

Sends buffered HTML output immediately

Redirect

Redirects the user to a different URL

Write

Writes a specified string to the output

Examples
Write text with ASP
This example demonstrates how to write text with ASP.
<html>
<body>
<%
response.write("Hello World!")
%>
</body>
</html>

127

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

Format text with HTML tags in ASP


This example demonstrates how to combine text and HTML tags with ASP.
<html>
<body>
<%
response.write("<h2>You can use HTML tags to format the text!</h2>")
%>
<%
response.write("<p style='color:#0000ff'>This text is styled with the style attribute!
</p>")
%>
</body>
</html>

Redirect the user to a different URL


This example demonstrates how to redirect the user to a different URL.
<%
if Request.Form("select")<>"" then
Response.Redirect(Request.Form("select"))
end if
%>
<html>
<body>
<form action="demo_redirect.asp" method="post">
<input type="radio" name="select"
value="demo_server.asp">
Server Example<br>
<input type="radio" name="select"
value="demo_text.asp">
Text Example<br><br>
<input type="submit" value="Go!">
</form>
</body>
</html>

Show a random link


This example demonstrates a link, each time you load the page, it will display one of two
links: W3Schools.com! OR Refsnesdata.no! There is a 50% chance for each of them.
<html>
<body>
<%
randomize()
r=rnd()
if r>0.5 then
response.write("<a href='http://www.w3schools.com'>W3Schools.com!</a>")
else
response.write("<a href='http://www.refsnesdata.no'>Refsnesdata.no!</a>")
end if
%>
<p>

128

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY


This example demonstrates a link, each time you load the page, it will display
one of two links: W3Schools.com! OR Refsnesdata.no! There is a 50% chance for
each of them.
</p>
</body>
</html>

output Result:
Refsnesdata.no!
This example demonstrates a link, each time you load the page, it will display one of two
links: W3Schools.com! OR Refsnesdata.no! There is a 50% chance for each of them.
Controlling the buffer
This example demonstrates how you can control the buffer.
<%
Response.Buffer=true
%>
<html>
<body>
<p>
This text will be sent to your browser when my response buffer is flushed.
</p>
<%
Response.Flush
%>
</body>
</html>

Clear the buffer


This example demonstrates how you can clear the buffer.
<%
Response.Buffer=true
%>
<html>
<body>
<p>This is some text I want to send to the user.</p>
<p>No, I changed my mind. I want to clear the text.</p>
<%
Response.Clear
%>
</body>
</html>

End a script in the middle of processing and return the result


This example demonstrates how to end a script in the middle of processing.
<html>
<body>
<p>I am writing some text. This text will never be<br>
<%
Response.End
%>
finished! It's too late to write more!</p>
</body>
</html>

129

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

Set how many minutes a page will be cached in a browser before it expires
This example demonstrates how to specify how many minutes a page will be cached in a
browser before it expires.
<%Response.Expires=-1%>
<html>
<body>
<p>This page will be refreshed with each access!</p>
</body>
</html>

Set a date/time when a page cached in a browser will expire


This example demonstrates how to specify a date/time a page cached in a browser will
expire.
<%
Response.ExpiresAbsolute=#May 05,2001 05:30:30#
%>
<html>
<body>
<p>This page will expire on May 05, 2001 05:30:30!</p>
</body>
</html>

Check if the user is still connected to the server


This example demonstrates how to check if a user is disconnected from the server.
<html>
<body>
<%
If Response.IsClientConnected=true then
Response.Write("The user is still connected!")
else
Response.Write("The user is not connected!")
end if
%>
</body>
</html>

Set the type of content


This example demonstrates how to specify the type of content.
<%
Response.ContentType="text/html"
%>
<html>
<body>
<p>This is some text</p>
</body>
</html>

ASP Request Object


130

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

The ASP Request object is used to get information from the user.

Request Object
When a browser asks for a page from a server, it is called a request. The ASP Request
object is used to get information from the user. Its collections, properties, and methods
are described below:

Collections
Collection

Description

ClientCertificate

Contains all the field values stored in the client certificate

Cookies

Contains all the cookie values sent in a HTTP request

Form

Contains all the form (input) values from a form that uses the post
method

QueryString

Contains all the variable values in a HTTP query string

ServerVariables

Contains all the server variable values

Properties
Property
TotalBytes

Description
Returns the total number of bytes the client sent in the body of the
request

Methods
Method
BinaryRead

Description
Retrieves the data sent to the server from the client as part of a post
request and stores it in a safe array

ASP Form collection


The Form collection is used to retrieve the values of form elements from a form that uses
the POST method.
Note: If you want to post large amounts of data (beyond 100 kb) the Request.Form
cannot be used.

Syntax
Request.Form(element)[(index)|.Count]

Parameter

Description

131

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

element

Required. The name of the form element from which the collection is to
retrieve values

index

Optional. Specifies one of multiple values for a parameter. From 1 to


Request.Form(parameter).Count.

Examples
Example 1
You can loop through all the values in a form request. If a user filled out a form by specifying
two values - Blue and Green - for the color element, you could retrieve those values like this:
<%
for i=1 to Request.Form("color").Count
Response.Write(Request.Form("color")(i) & "<br />")
next
%>

Output:
Blue
Green

Example 2
Consider the following form:
<form action="submit.asp" method="post">
<p>First name: <input name="firstname"></p>
<p>Last name: <input name="lastname"></p>
<p>Your favorite color:
<select name="color">
<option>Blue</option>
<option>Green</option>
<option>Red</option>
<option>Yellow</option>
<option>Pink</option>
</select>
</p>
<p><input type="submit"></p>
</form>

The following request might be sent:


firstname=John&lastname=Dove&color=Red

Now we can use the information from the form in a script:


Hi, <%=Request.Form("firstname")%>.
Your favorite color is <%=Request.Form("color")%>.

Output:
Hi, John. Your favorite color is Red.

If you do not specify any element to display, like this:


Form data is: <%=Request.Form%>

the output would look like this:


Form data is: firstname=John&lastname=Dove&color=Red

132

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

ASP QueryString Collection


The QueryString collection is used to retrieve the variable values in the HTTP query
string.
The HTTP query string is specified by the values following the question mark (?), like
this:
<a href= "test.asp?txt=this is a query string test">Link with a query string</a>
The line above generates a variable named txt with the value "this is a query string test".
Query strings are also generated by form submission, or by a user typing a query into the
address bar of the browser.

Syntax
Request.QueryString(variable)[(index)|.Count]

Parameter

Description

variable

Required. The name of the variable in the HTTP query string to retrieve

index

Optional. Specifies one of multiple values for a variable. From 1 to


Request.QueryString(variable).Count

Examples
Example 1
To loop through all the n variable values in a Query String:
The following request is sent:
http://www.w3schools.com/test/names.asp?n=John&n=Susan

and names.asp contains the following script:


<%
for i=1 to Request.QueryString("n").Count
Response.Write(Request.QueryString("n")(i) & "<br />")
next
%>

The file names.asp would display the following:


John
Susan

Example 2
The following string might be sent:
http://www.w3schools.com/test/names.asp?name=John&age=30

this results in the following QUERY_STRING value:


name=John&age=30

Now we can use the information in a script:


Hi, <%=Request.QueryString("name")%>.
Your age is <%= Request.QueryString("age")%>.

Output:

133

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY


Hi, John. Your age is 30.

If you do not specify any variable values to display, like this:


Query string is: <%=Request.QueryString%>

the output would look like this:


Query string is: name=John&age=30

QueryString Collection Examples


Send query information when a user clicks on a link
This example demonstrates how to send some extra query information to a page within a
link, and retrieve that information on the destination page (which is, in this example, the
same page).
<html>
<body>
<a href="demo_simplequerystring.asp?color=green">Example</a>
<%
Response.Write(Request.QueryString)
%>
</body>
</html>

A QueryString collection in its simplest use


This example demonstrates how the QueryString collection retrieves the values from a
form. The form uses the GET method, which means that the information sent is visible to
everybody (in the address field). The GET method also limits the amount of information
that can be sent.
<html>
<body>
<form action="demo_simplereqquery.asp" method="get">
First name: <input type="text" name="fname"><br>
Last name: <input type="text" name="lname"><br>
<input type="submit" value="Submit">
</form>
<%
Response.Write(Request.QueryString)
%>
</body>
</html>

How to use information from forms


This example demonstrates how to use the values retrieved from a form. We use the
QueryString collection. The form uses the get method.
<html>
<body>
<form action="demo_reqquery.asp" method="get">
Your name: <input type="text" name="fname" size="20" />
<input type="submit" value="Submit" />
</form>
<%
dim fname
fname=Request.QueryString("fname")
If fname<>"" Then

134

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY


Response.Write("Hello " & fname & "!<br />")
Response.Write("How are you today?")
End If
%>
</body>
</html>

More information from a form


This example demonstrates what the QueryString contains if several input fields have
the same name. It shows how to separate input fields with equal names from each other. It
also shows how to use the Count keyword to count the "name" property. The form uses
the get method.
<html>
<body>
<%
If Request.QueryString<>"" Then
If Request.QueryString("name")<>", " Then
name1=Request.QueryString("name")(1)
name2=Request.QueryString("name")(2)
end if
end if
%>
<form action="demo_reqquery2.asp" method="get">
First name:
<input type="text" name="name" value="<%=name1%>" />
<br />
Last name:
<input type="text" name="name" value="<%=name2%>" />
<br />
<input type="submit" value="Submit" />
</form>
<hr>
<%
If Request.QueryString<>"" Then
Response.Write("<p>")
Response.Write("The information received from the form was:")
Response.Write("</p><p>")
Response.Write("name=" & Request.QueryString("name"))
Response.Write("</p><p>")
Response.Write("The name property's count is: ")
Response.Write(Request.QueryString("name").Count)
Response.Write("</p><p>")
Response.Write("First name=" & name1)
Response.Write("</p><p>")
Response.Write("Last name=" & name2)
Response.Write("</p>")
end if
%>
</body>
</html>

Form Collection Examples


A form collection in its simplest use
This example demonstrates how the Form collection retrieves the values from a form.

135

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

The form uses the POST method, which means that the information sent is invisible to
others, and it has no limits (you can send a large amount of information).
<html>
<body>
<form action="demo_simpleform1.asp" method="post">
First name:
<input type="text" name="fname" value="Donald" />
<br />
Last name:
<input type="text" name="lname" value="Duck" />
<br />
<input type="submit" value="Submit" />
</form>
<%
Response.Write(Request.Form)
%>
</body>
</html>

How to use information from forms


This example demonstrates how to use the values retrieved from a form. We use the
Form collection. The form uses the post method.
<html>
<body>
<form action="demo_simpleform.asp" method="post">
Your name: <input type="text" name="fname" size="20" />
<input type="submit" value="Submit" />
</form>
<%
dim fname
fname=Request.Form("fname")
If fname<>"" Then
Response.Write("Hello " & fname & "!<br />")
Response.Write("How are you today?")
End If
%>
</body>
</html>

More information from a form


This example demonstrates what the Form collection contains if several input fields have
the same name. It shows how to separate input fields with equal names from each other. It
also shows how to use the Count keyword to count the "name" property. The form uses
the post method.
<html>
<body>
<form action="demo_form2.asp" method="post">
First name:
<input type="text" name="name" value="Donald" />
<br />
Last name:
<input type="text" name="name" value="Duck" />

136

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY


<br />
<input type="submit" value="Submit" />
</form>
<hr />
<p>The information received from the form above was:</p>
<%
If Request.Form("name")<>"" Then
Response.Write("<p>")
Response.Write("name=" & Request.Form("name"))
Response.Write("</p><p>")
Response.Write("The name property's count is: ")
Response.Write(Request.Form("name").Count)
Response.Write("</p><p>")
Response.Write("First name=" & Request.Form("name")(1))
Response.Write("</p><p>")
Response.Write("Last name=" & Request.Form("name")(2))
Response.Write("</p>")
End if
%>
</body>
</html>

A form with radio buttons


This example demonstrates how to interact with the user through radio buttons, with the
Form collection. The form uses the post method.
<html>
<%
dim cars
cars=Request.Form("cars")
%>
<body>
<form action="demo_radiob.asp" method="post">
<p>Please select your favorite car:</p>
<input type="radio" name="cars"
<%if cars="Volvo" then Response.Write("checked")%>
value="Volvo">Volvo</input>
<br />
<input type="radio" name="cars"
<%if cars="Saab" then Response.Write("checked")%>
value="Saab">Saab</input>
<br />
<input type="radio" name="cars"
<%if cars="BMW" then Response.Write("checked")%>
value="BMW">BMW</input>
<br /><br />
<input type="submit" value="Submit" />
</form>
<%
if cars<>"" then
Response.Write("<p>Your favorite car is: " & cars & "</p>")
end if
%>
</body>
</html>

137

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

A form with checkboxes


This example demonstrates how to interact with the user through checkboxes, with the
Form collection. The form uses the post method.
<html>
<body>
<%
fruits=Request.Form("fruits")
%>
<form action="demo_checkboxes.asp" method="post">
<p>Which of these fruits do you prefer:</p>
<input type="checkbox" name="fruits" value="Apples"
<%if instr(fruits,"Apple") then Response.Write("checked")%>>
Apple
<br>
<input type="checkbox" name="fruits" value="Oranges"
<%if instr(fruits,"Oranges") then Response.Write("checked")%>>
Orange
<br>
<input type="checkbox" name="fruits" value="Bananas"
<%if instr(fruits,"Banana") then Response.Write("checked")%>>
Banana
<br>
<input type="submit" value="Submit">
</form>
<%
if fruits<>"" then%>
<p>You like: <%Response.Write(fruits)%></p>
<%end if
%>
</body>
</html>

Other Examples
Get the server variables
This example demonstrates how to find out the visitors (yours) browser type, IP address,
and more with the ServerVariables collection.
<html>
<body>
<p>
<b>You are browsing this site with:</b>
<%Response.Write(Request.ServerVariables("http_user_agent"))%>
</p>
<p>
<b>Your IP address is:</b>
<%Response.Write(Request.ServerVariables("remote_addr"))%>
</p>
<p>
<b>The DNS lookup of the IP address is:</b>
<%Response.Write(Request.ServerVariables("remote_host"))%>
</p>

138

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY


<p>
<b>The method used to call the page:</b>
<%Response.Write(Request.ServerVariables("request_method"))%>
</p>
<p>
<b>The server's domain name:</b>
<%Response.Write(Request.ServerVariables("server_name"))%>
</p>
<p>
<b>The server's port:</b>
<%Response.Write(Request.ServerVariables("server_port"))%>
</p>
<p>
<b>The server's software:</b>
<%Response.Write(Request.ServerVariables("server_software"))%>
</p>
</body>
</html>

You are browsing this site with: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;
SV1; Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1) ; MEGAUPLOAD
2.0)
Your IP address is: 59.92.8.182
The DNS lookup of the IP address is: 59.92.8.182
The method used to call the page: GET
The server's domain name: www.w3schools.com
The server's port: 80
The server's software: Microsoft-IIS/6.0
Create a welcome cookie
This example demonstrates how to create a Welcome Cookie with the Cookies
Collection.
<%
dim numvisits
response.cookies("NumVisits").Expires=date+365
numvisits=request.cookies("NumVisits")
if numvisits="" then
response.cookies("NumVisits")=1
response.write("Welcome! This is the first time you are visiting this Web page.")
else
response.cookies("NumVisits")=numvisits+1
response.write("You have visited this ")
response.write("Web page " & numvisits)
if numvisits=1 then
response.write " time before!"
else
response.write " times before!"
end if
end if

139

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY


%>
<html>
<body>
</body>
</html>

Find the total number of bytes the user sent


This example demonstrates how to use the TotalBytes property to find out the total
number of bytes the user sent in the Request object.
html>
<body>
<form action="demo_totalbytes.asp" method="post">
Please type something:
<input type="text" name="txt"><br><br>
<input type="submit" value="Submit">
</form>
<%
If Request.Form("txt")<>"" Then
Response.Write("You submitted: ")
Response.Write(Request.Form)
Response.Write("<br><br>")
Response.Write("Total bytes: ")
Response.Write(Request.Totalbytes)
End If
%>
</body>
</html>

ASP Server Object


The ASP Server object is used to access properties and methods on the server.

Server Object
The ASP Server object is used to access properties and methods on the server. Its
properties and methods are described below:

Properties
Property
ScriptTimeout

Description
Sets or returns the maximum number of seconds a script can run before
it is terminated

Methods
Method
CreateObject

Description
Creates an instance of an object

140

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

Execute

Executes an ASP file from inside another ASP file

GetLastError()

Returns an ASPError object that describes the error condition that


occurred

HTMLEncode

Applies HTML encoding to a specified string

MapPath

Maps a specified path to a physical path

Transfer

Sends (transfers) all the information created in one ASP file to a second
ASP file

URLEncode

Applies URL encoding rules to a specified string

ASP ScriptTimeout Property


The ScriptTimeout property sets or returns the maximum number of seconds a script can
run before it is terminated.

Syntax
Server.ScriptTimeout[=NumSeconds]

Parameter
NumSeconds

Description
The maximum number of seconds a script can run before the server
terminates it. Default is 90 seconds

Examples
Example 1
Set the script timeout:
<%
Server.ScriptTimeout=200
%>

Example 2
Retrieve the current value of the ScriptTimeout property:
<%
response.write(Server.ScriptTimeout)
%>

ASP CreateObject Method


The CreateObject method creates an instance of an object.
Note: Objects created with this method have page scope. They are destroyed when the
server are finished processing the current ASP page. To create an object with session or

141

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

application scope, you can either use the <object> tag in the Global.asa file, or store the
object in a session or application variable.

Syntax
Server.CreateObject(progID)

Part
progID

Description
Required. The type of object to create

Example
Example 1
This example creates an instance of the server component MSWC.AdRotator:
<%
Set adrot=Server.CreateObject("MSWC.AdRotator")
%>

Example 2
An object stored in a session variable is destroyed when the session ends. However, you can
also destroy the object by setting the variable to Nothing or to a new value:
<%
Session("ad")=Nothing
%>
or
<%
Session("ad")="a new value"
%>

Example 3
You cannot create an instance of an object with the same name as a built-in object:
<%
Set Application=Server.CreateObject("Application")

ASP Execute Method


The Execute method executes an ASP file from inside another ASP file. After executing
the called .asp file, the control is returned to the original .asp file.

Syntax
Server.Execute(path)

Parameter
path

Description
Required. The location of the ASP file to execute

Example
File1.asp:

142

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY


<%
response.write("I am in File 1!<br />")
Server.Execute("file2.asp")
response.write("I am back in File 1!")
%>

File2.asp:
<%
response.write("I am in File 2!<br />")
%>

Output:
I am in File 1!
I am in File 2!
I am back in File 1!

Also look at the Server.Transfer method to see the difference between the Server.Execute
and Server.Transfer methods.

Examples
When was a file last modified?
Checks when this file was last modified.
<html>
<body>
<%
Set fs = Server.CreateObject("Scripting.FileSystemObject")
Set rs = fs.GetFile(Server.MapPath("demo_lastmodified.asp"))
modified = rs.DateLastModified
%>
This file was last modified on: <%response.write(modified)
Set rs = Nothing
Set fs = Nothing
%>
</body>
</html>

This file was last modified on: 12/09/2006 07:40:45


Open a text file for reading
This example opens the file "Textfile.txt" for reading.
<html>
<body>
<%
Set FS = Server.CreateObject("Scripting.FileSystemObject")
Set RS = FS.OpenTextFile(Server.MapPath("text") & "\TextFile.txt",1)
While not rs.AtEndOfStream
Response.Write RS.ReadLine
Response.Write("<br />")
Wend

143

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY


%>
<p>
<a href="text/textfile.txt"><img border="0" src="/images/btn_view_text.gif"></a>
</p>
</body>
</html>

Hello World line 1


Hello World line 2
Hello World line 3

Homemade hit counter


This example reads a number from a file, adds 1 to the number, and writes the number
back to the file.
<%
Set FS=Server.CreateObject("Scripting.FileSystemObject")
Set RS=FS.OpenTextFile(Server.MapPath("counter.txt"), 1, False)
fcount=RS.ReadLine
RS.Close
fcount=fcount+1
'This code is disabled due to the write access security on our server:
'Set RS=FS.OpenTextFile(Server.MapPath("counter.txt"), 2, False)
'RS.Write fcount
'RS.Close
Set RS=Nothing
Set FS=Nothing
%>
<html>
<body>
<p>
This page has been visited <%=fcount%> times.
</p>
</body>
</html>

This page has been visited 12345 times

ASP FileSystemObject Object


The FileSystemObject object is used to access the file system on the server.

The FileSystemObject Object


The FileSystemObject object is used to access the file system on the server. This object

144

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

can manipulate files, folders, and directory paths. It is also possible to retrieve file system
information with this object.
The following code creates a text file (c:\test.txt) and then writes some text to the file:
<%
dim fs,fname
set fs=Server.CreateObject("Scripting.FileSystemObject")
set fname=fs.CreateTextFile("c:\test.txt",true)
fname.WriteLine("Hello World!")
fname.Close
set fname=nothing
set fs=nothing
%>

The FileSystemObject object's properties and methods are described below:

Properties
Property
Drives

Description
Returns a collection of all Drive objects on the computer

Methods
Method

Description

BuildPath

Appends a name to an existing path

CopyFile

Copies one or more files from one location to another

CopyFolder

Copies one or more folders from one location to another

CreateFolder

Creates a new folder

CreateTextFile

Creates a text file and returns a TextStream object that can be


used to read from, or write to the file

DeleteFile

Deletes one or more specified files

DeleteFolder

Deletes one or more specified folders

DriveExists

Checks if a specified drive exists

FileExists

Checks if a specified file exists

FolderExists

Checks if a specified folder exists

GetAbsolutePathName

Returns the complete path from the root of the drive for the
specified path

145

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

GetBaseName

Returns the base name of a specified file or folder

GetDrive

Returns a Drive object corresponding to the drive in a specified


path

GetDriveName

Returns the drive name of a specified path

GetExtensionName

Returns the file extension name for the last component in a


specified path

GetFile

Returns a File object for a specified path

GetFileName

Returns the file name or folder name for the last component in a
specified path

GetFolder

Returns a Folder object for a specified path

GetParentFolderName

Returns the name of the parent folder of the last component in a


specified path

GetSpecialFolder

Returns the path to some of Windows' special folders

GetTempName

Returns a randomly generated temporary file or folder

MoveFile

Moves one or more files from one location to another

MoveFolder

Moves one or more folders from one location to another

OpenTextFile

Opens a file and returns a TextStream object that can be used to


access the file

Examples
Does a specified file exist?
This example demonstrates how to first create a FileSystemObject Object, and then use
the FileExists method to check if the file exists.
<html>
<body>
<%
Set fs=Server.CreateObject("Scripting.FileSystemObject")
If (fs.FileExists("c:\winnt\cursors\3dgarro.cur"))=true Then
Response.Write("File c:\winnt\cursors\3dgarro.cur exists.")
Else
Response.Write("File c:\winnt\cursors\3dgarro.cur does not exist.")
End If
set fs=nothing
%>
</body>
</html>

Does a specified folder exist?


This example demonstrates how to use the FolderExists method to check if a folder
exists.

146

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY


<html>
<body>
<%
Set fs=Server.CreateObject("Scripting.FileSystemObject")
If fs.FolderExists("c:\temp") = true Then
Response.Write("Folder c:\temp exists.")
Else
Response.Write("Folder c:\temp does not exist.")
End If
set fs=nothing
%>

Does a specified drive exist?


This example demonstrates how to use the DriveExists method to check if a drive exists.
<html>
<body>
<%
Set fs=Server.CreateObject("Scripting.FileSystemObject")
if fs.driveexists("c:") = true then
Response.Write("Drive c: exists.")
Else
Response.Write("Drive c: does not exist.")
End If
Response.write("<br>")
if fs.driveexists("g:") = true then
Response.Write("Drive g: exists.")
Else
Response.Write("Drive g: does not exist.")
End If
set fs=nothing
%>
</body>
</html>

Get the name of a specified drive


This example demonstrates how to use the GetDriveName method to get the name of a
specified drive.
<html>
<body>
<%
Set fs=Server.CreateObject("Scripting.FileSystemObject")
p=fs.GetDriveName("c:\winnt\cursors\3dgarro.cur")
Response.Write("The drive name is: " & p)
set fs=nothing
%>
</body>
</html>

Get the name of the parent folder of a specified path


This example demonstrates how to use the GetParentFolderName method to get the name
of the parent folder of a specified path.
147

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY


<html>
<body>
<%
Set fs=Server.CreateObject("Scripting.FileSystemObject")
p=fs.GetParentFolderName("c:\winnt\cursors\3dgarro.cur")
Response.Write("The parent folder name of c:\winnt\cursors\3dgarro.cur is: " & p)
set fs=nothing
%>
</body>
</html>

The parent folder name of c:\winnt\cursors\3dgarro.cur is: c:\winnt\cursors


Get the file extension
This example demonstrates how to use the GetExtensionName method to get the file
extension of the last component in a specified path.
<html>
<body>
<%
Set fs=Server.CreateObject("Scripting.FileSystemObject")
Response.Write("The file extension of the file 3dgarro is: ")
Response.Write(fs.GetExtensionName("c:\winnt\cursors\3dgarro.cur"))
set fs=nothing
%>
</body>
</html>

The file extension of the file 3dgarro is: cur


Get file name
This example demonstrates how to use the GetFileName method to get the file name of
the last component in a specified path.
<html>
<body>
<%
Set fs=Server.CreateObject("Scripting.FileSystemObject")
Response.Write("The file name of the last component is: ")
Response.Write(fs.GetFileName("c:\winnt\cursors\3dgarro.cur"))
set fs=nothing
%>
</body>
</html>

Get the base name of a file or folder


This example demonstrates how to use the GetBaseName method to return the base name
of the file or folder, in a specified path.
<html>
<body>
<%
Set fs=Server.CreateObject("Scripting.FileSystemObject")
Response.Write(fs.GetBaseName("c:\winnt\cursors\3dgarro.cur"))
Response.Write("<br />")
Response.Write(fs.GetBaseName("c:\winnt\cursors\"))
Response.Write("<br />")
Response.Write(fs.GetBaseName("c:\winnt\"))
set fs=nothing

148

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY


%>
</body>
</html>

3dgarro
cursors
winnt

ASP OpenTextFile Method


The OpenTextFile method opens a specified file and returns a TextStream object that can
be used to access the file.

Syntax
FileSystemObject.OpenTextFile(fname,mode,create,format)

Parameter

Description

fname

Required. The name of the file to open

mode

Optional. How to open the file


1=ForReading - Open a file for reading. You cannot write to this file.
2=ForWriting - Open a file for writing.
8=ForAppending - Open a file and write to the end of the file.

create

Optional. Sets whether a new file can be created if the filename does not
exist. True indicates that a new file can be created, and False indicates that a
new file will not be created. False is default

format

Optional. The format of the file


0=TristateFalse - Open the file as ASCII. This is default.
-1=TristateTrue - Open the file as Unicode.
-2=TristateUseDefault - Open the file using the system default.

Example
<%
dim fs,f
set fs=Server.CreateObject("Scripting.FileSystemObject")
set f=fs.OpenTextFile(Server.MapPath("testread.txt"),8,true)
f.WriteLine("This text will be added to the end of file")
f.Close
set f=Nothing
set fs=Nothing
%>

ASP CreateTextFile Method


The CreateTextFile method creates a new text file in the current folder and returns a
TextStream object that can be used to read from, or write to the file.

149

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

Syntax
FileSystemObject.CreateTextFile(filename[,overwrite[,unicode]])
FolderObject.CreateTextFile(filename[,overwrite[,unicode]])

Parameter

Description

filename

Required. The name of the file to create

overwrite

Optional. A Boolean value that indicates whether an existing file can be


overwritten. True indicates that the file can be overwritten and False
indicates that the file can not be overwritten. Default is True

unicode

Optional. A Boolean value that indicates whether the file is created as a


Unicode or an ASCII file. True indicates that the file is created as a Unicode
file, False indicates that the file is created as an ASCII file. Default is False

Example for the FileSystemObject object


<%
dim fs,tfile
set fs=Server.CreateObject("Scripting.FileSystemObject")
set tfile=fs.CreateTextFile("c:\somefile.txt")
tfile.WriteLine("Hello World!")
tfile.close
set tfile=nothing
set fs=nothing
%>

Example for the Folder object


<%
dim fs,fo,tfile
Set fs=Server.CreateObject("Scripting.FileSystemObject")
Set fo=fs.GetFolder("c:\test")
Set tfile=fo.CreateTextFile("test.txt",false)
tfile.WriteLine("Hello World!")
tfile.Close
set tfile=nothing
set fo=nothing
set fs=nothing
%>

ASP TextStream Object


The TextStream object is used to access the contents of a text file.

The TextStream Object


The TextStream object is used to access the contents of text files.
The following code creates a text file (c:\test.txt) and then writes some text to the file (the
variable f is an instance of the TextStream object):
<%
dim fs, f
set fs=Server.CreateObject("Scripting.FileSystemObject")

150

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY


set f=fs.CreateTextFile("c:\test.txt",true)
f.WriteLine("Hello World!")
f.Close
set f=nothing
set fs=nothing
%>

To create an instance of the TextStream object you can use the CreateTextFile or
OpenTextFile methods of the FileSystemObject object, or you can use the
OpenAsTextStream method of the File object.
The TextStream object's properties and methods are described below:

Properties
Property

Description

AtEndOfLine

Returns true if the file pointer is positioned immediately before the endof-line marker in a TextStream file, and false if not

AtEndOfStream

Returns true if the file pointer is at the end of a TextStream file, and
false if not

Column

Returns the column number of the current character position in an input


stream

Line

Returns the current line number in a TextStream file

Methods
Method

Description

Close

Closes an open TextStream file

Read

Reads a specified number of characters from a TextStream file and


returns the result

ReadAll

Reads an entire TextStream file and returns the result

ReadLine

Reads one line from a TextStream file and returns the result

Skip

Skips a specified number of characters when reading a TextStream file

SkipLine

Skips the next line when reading a TextStream file

Write

Writes a specified text to a TextStream file

WriteLine

Writes a specified text and a new-line character to a TextStream file

WriteBlankLines

Writes a specified number of new-line character to a TextStream file

151

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

Examples
Read textfile
This example demonstrates how to use the OpenTextFile method of the FileSystemObject
to create a TextStream Object. The ReadAll method of the TextStream Object reads from
the opened text file.
<html>
<body>
<p>This is the text in the text file:</p>
<%
Set fs=Server.CreateObject("Scripting.FileSystemObject")
Set f=fs.OpenTextFile(Server.MapPath("testread.txt"), 1)
Response.Write(f.ReadAll)
f.Close
Set f=Nothing
Set fs=Nothing
%>
</body>
</html>

Read only a part of a textfile


This example demonstrates how to only read a part of a TextStream file.
<html>
<body>
<p>This is the first five characters from the text file:</p>
<%
Set fs=Server.CreateObject("Scripting.FileSystemObject")
Set f=fs.OpenTextFile(Server.MapPath("testread.txt"), 1)
Response.Write(f.Read(5))
f.Close
Set f=Nothing
Set fs=Nothing
%>
</body>
</html>

This is the first five characters from the text file:


Hello

Read one line of a textfile


This example demonstrates how to read one line from a TextStream file.

152

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY


<html>
<body>
<p>This is the first line of the text file:</p>
<%
Set fs=Server.CreateObject("Scripting.FileSystemObject")
Set f=fs.OpenTextFile(Server.MapPath("testread.txt"), 1)
Response.Write(f.ReadLine)
f.Close
Set f=Nothing
Set fs=Nothing
%>
</body>
</html>

This is the first line of the text file:


Hello!
Read all lines from a textfile
This example demonstrates how to read all the lines from a TextStream file.
<html>
<body>
<p>This is all the lines in the text file:</p>
<%
Set fs=Server.CreateObject("Scripting.FileSystemObject")
Set f=fs.OpenTextFile(Server.MapPath("testread.txt"), 1)
do while f.AtEndOfStream = false
Response.Write(f.ReadLine)
Response.Write("<br>")
loop
f.Close
Set f=Nothing
Set fs=Nothing
%>
</body>
</html>

Skip a part of a textfile


This example demonstrates how to skip a specified number of characters when reading
the TextStream file.
<html>
<body>
<p>The first four characters in the text file are skipped:</p>

153

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY


<%
Set fs=Server.CreateObject("Scripting.FileSystemObject")
Set f=fs.OpenTextFile(Server.MapPath("testread.txt"), 1)
f.Skip(4)
Response.Write(f.ReadAll)
f.Close
Set f=Nothing
Set fs=Nothing
%>
</body>
</html>

The first four characters in the text file are skipped:


o! How are you today?
Skip a line of a textfile
This example demonstrates how to skip a line when reading the TextStream file.
<html>
<body>
<p>The first line in the text file is skipped:</p>
<%
Set fs=Server.CreateObject("Scripting.FileSystemObject")
Set f=fs.OpenTextFile(Server.MapPath("testread.txt"), 1)
f.SkipLine
Response.Write(f.ReadAll)
f.Close
Set f=Nothing
Set fs=Nothing
%>
</body>
</html>

Return line-number
This example demonstrates how to return the current line number in a TextStream file.
<html>
<body>
<p>This is all the lines in the text file (with line numbers):</p>
<%
Set fs=Server.CreateObject("Scripting.FileSystemObject")
Set f=fs.OpenTextFile(Server.MapPath("testread.txt"), 1)

154

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY


do while f.AtEndOfStream = false
Response.Write("Line:" & f.Line & " ")
Response.Write(f.ReadLine)
Response.Write("<br>")
loop
f.Close
Set f=Nothing
Set fs=Nothing
%>
</body>
</html>

This is all the lines in the text file (with line numbers):
Line:1 Hello!
Line:2 How are you today?

Get column number


This example demonstrates how to get the column number of the current character in a
file.
<html>
<body>
<%
Set fs=Server.CreateObject("Scripting.FileSystemObject")
Set f=fs.OpenTextFile(Server.MapPath("testread.txt"), 1)
Response.Write(f.Read(2))
Response.Write("<p>The cursor is now standing in position " & f.Column & " in the
text file.</p>")
f.Close
Set f=Nothing
Set fs=Nothing
%>
</body>
</html>

He
The cursor is now standing in position 3 in the text file.

155

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

ASP WriteLine Method


The WriteLine method writes a specified text and a new-line character to a TextStream
file.

Syntax
TextStreamObject.WriteLine(text)

Parameter
text

Description
Optional. The text to write to the file. If you do not specify this parameter, a
new-line character will be written to the file

Example
<%
dim fs,f
set fs=Server.CreateObject("Scripting.FileSystemObject")
set f=fs.CreateTextFile("c:\test.txt",true)
f.WriteLine("Hello World!")
f.WriteLine("How are you today?")
f.WriteLine("Goodbye!")
f.close
set f=nothing
set fs=nothing
%>

The file test.txt will look like this after executing the code above:
Hello World!
How are you today?
Goodbye!

ASP Write Method


The Write method writes a specified text to a TextStream file.
Note: This method write text to the TextStream file with no spaces or line breaks between
each string.

Syntax
TextStreamObject.Write(text)

Parameter
text

Description
Required. The text to write to the file

156

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

Example
<%
dim fs,f
set fs=Server.CreateObject("Scripting.FileSystemObject")
set f=fs.CreateTextFile("c:\test.txt",true)
f.write("Hello World!")
f.write("How are you today?")
f.close
set f=nothing
set fs=nothing
%>

The file test.txt will look like this after executing the code above:
Hello World!How are you today?

ASP WriteBlankLines Method


The WriteBlankLines method writes a specified number of new-line characters to a
TextStream file.

Syntax
TextStreamObject.WriteBlankLines(numlines)

Parameter
numlines

Description
Required. The number of new-line characters to write to the file

Example
<%
dim fs,f
set fs=Server.CreateObject("Scripting.FileSystemObject")
set f=fs.CreateTextFile("c:\test.txt",true)
f.WriteLine("Hello World!")
f.WriteBlankLines(2)
f.WriteLine("How are you today?")
f.close
set f=nothing
set fs=nothing
%>

The file test.txt will look like this after executing the code above:
Hello World!
How are you today?

157

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

Introduction to ADO
ADO can be used to access databases from your web pages.

Accessing a Database from an ASP Page


The common way to access a database from inside an ASP page is to:
Create an ADO connection to a database
Open the database connection
Create an ADO recordset
158

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

Open the recordset


Extract the data you need from the recordset
Close the recordset
Close the connection

What is ADO?
ADO is a Microsoft technology
ADO stands for ActiveX Data Objects
ADO is a Microsoft Active-X component
ADO is automatically installed with Microsoft IIS
ADO is a programming interface to access data in a database

ADO Connection Object


Connection Object
The ADO Connection Object is used to create and open connection to a data
source. Through this connection, you can access and manipulate a database.
If you want to access a database multiple times, you should establish a connection
using the Connection object. You can also make a connection to a database by
passing a connection string via a Command or Recordset object. However, this
type of connection is only good for one specific, single query.
ProgID
set objConnection=Server.CreateObject("ADODB.connection")

Properties
Property

Description

Attributes

Sets or returns the attributes of a Connection object

CommandTimeout

Sets or returns the number of seconds to wait while


attempting to execute a command

ConnectionString

Sets or returns the details used to create a connection to a data


source

ConnectionTimeout

Sets or returns the number of seconds to wait for a connection

159

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

to open
CursorLocation

Sets or returns the location of the cursor service

DefaultDatabase

Sets or returns the default database name

IsolationLevel

Sets or returns the isolation level

Mode

Sets or returns the provider access permission

Provider

Sets or returns the provider name

State

Returns a value describing if the connection is open or closed

Version

Returns the ADO version number

Methods
Method

Description

BeginTrans

Begins a new transaction

Cancel

Cancels an execution

Close

Closes a connection

CommitTrans

Saves any changes and ends the current transaction

Execute

Executes a query, statement, procedure or provider specific


text

Open

Opens a connection

OpenSchema

Returns schema information from the provider about the data


source

RollbackTrans

Cancels any changes in the current transaction and ends the


transaction

Events
Note: You cannot handle events using VBScript or JScript (only Visual Basic,
Visual C++, and Visual J++ languages can handle events).
Event

Description

BeginTransComplete

Triggered after the BeginTrans operation

CommitTransComplete

Triggered after the CommitTrans operation

ConnectComplete

Triggered after a connection starts


160

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

Disconnect

Triggered after a connection ends

ExecuteComplete

Triggered after a command has finished executing

InfoMessage

Triggered if a warning occurs during a ConnectionEvent


operation

RollbackTransComplete

Triggered after the RollbackTrans operation

WillConnect

Triggered before a connection starts

WillExecute

Triggered before a command is executed

Collections
Collection

Description

Errors

Contains all the Error objects of the Connection object

Properties

Contains all the Property objects of the Connection object

ADO Recordset Object


Recordset Object
The ADO Recordset object is used to hold a set of records from a database table. A
Recordset object consist of records and columns (fields).
In ADO, this object is the most important and the one used most often to
manipulate data from a database.
ProgID
set objRecordset=Server.CreateObject("ADODB.recordset")
When you first open a Recordset, the current record pointer will point to the first
record and the BOF and EOF properties are False. If there are no records, the BOF
and EOF property are True.
Recordset objects can support two types of updating:
Immediate updating - all changes are written immediately to the database
once you call the Update method.
Batch updating - the provider will cache multiple changes and then send
them to the database with the UpdateBatch method.
In ADO there are 4 different cursor types defined:
Dynamic cursor - Allows you to see additions, changes, and deletions by
other users.
Keyset cursor - Like a dynamic cursor, except that you cannot see
161

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

additions by other users, and it prevents access to records that other users
have deleted. Data changes by other users will still be visible.
Static cursor - Provides a static copy of a recordset for you to use to find
data or generate reports. Additions, changes, or deletions by other users will
not be visible. This is the only type of cursor allowed when you open a
client-side Recordset object.
Forward-only cursor - Allows you to only scroll forward through the
Recordset. Additions, changes, or deletions by other users will not be
visible.
The cursor type can be set by the CursorType property or by the CursorType
parameter in the Open method.
Note: Not all providers support all methods or properties of the Recordset object.
Properties
Property

Description

AbsolutePage

Sets or returns a value that specifies the page number in


the Recordset object

AbsolutePosition

Sets or returns a value that specifies the ordinal position


of the current record in the Recordset object

ActiveCommand

Returns the Command object associated with the


Recordset

ActiveConnection

Sets or returns a definition for a connection if the


connection is closed, or the current Connection object if
the connection is open

BOF

Returns true if the current record position is before the


first record, otherwise false

Bookmark

Sets or returns a bookmark. The bookmark saves the


position of the current record

CacheSize

Sets or returns the number of records that can be cached

CursorLocation

Sets or returns the location of the cursor service

CursorType

Sets or returns the cursor type of a Recordset object

DataMember

Sets or returns the name of the data member that will be


retrieved from the object referenced by the DataSource
property

162

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

DataSource

Specifies an object containing data to be represented as a


Recordset object

EditMode

Returns the editing status of the current record

EOF

Returns true if the current record position is after the last


record, otherwise false

Filter

Sets or returns a filter for the data in a Recordset object

Index

Sets or returns the name of the current index for a


Recordset object

LockType

Sets or returns a value that specifies the type of locking


when editing a record in a Recordset

MarshalOptions

Sets or returns a value that specifies which records are to


be returned to the server

MaxRecords

Sets or returns the maximum number of records to return


to a Recordset object from a query

PageCount

Returns the number of pages with data in a Recordset


object

PageSize

Sets or returns the maximum number of records allowed


on a single page of a Recordset object

RecordCount

Returns the number of records in a Recordset object

Sort

Sets or returns the field names in the Recordset to sort on

Source

Sets a string value or a Command object reference, or


returns a String value that indicates the data source of the
Recordset object

State

Returns a value that describes if the Recordset object is


open, closed, connecting, executing or retrieving data

Status

Returns the status of the current record with regard to


batch updates or other bulk operations

StayInSync

Sets or returns whether the reference to the child records


will change when the parent record position changes

Methods
Method

Description

163

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

AddNew

Creates a new record

Cancel

Cancels an execution

CancelBatch

Cancels a batch update

CancelUpdate

Cancels changes made to a record of a Recordset object

Clone

Creates a duplicate of an existing Recordset

Close

Closes a Recordset

CompareBookmarks

Compares two bookmarks

Delete

Deletes a record or a group of records

Find

Searches for a record in a Recordset that satisfies a


specified criteria

GetRows

Copies multiple records from a Recordset object into a


two-dimensional array

GetString

Returns a Recordset as a string

Move

Moves the record pointer in a Recordset object

MoveFirst

Moves the record pointer to the first record

MoveLast

Moves the record pointer to the last record

MoveNext

Moves the record pointer to the next record

MovePrevious

Moves the record pointer to the previous record

NextRecordset

Clears the current Recordset object and returns the next


Recordset object by looping through a series of
commands

Open

Opens a database element that gives you access to


records in a table, the results of a query, or to a saved
Recordset

Requery

Updates the data in a Recordset by re-executing the


query that made the original Recordset

Resync

Refreshes the data in the current Recordset from the


original database

Save

Saves a Recordset object to a file or a Stream object

164

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

Seek

Searches the index of a Recordset to find a record that


matches the specified values

Supports

Returns a boolean value that defines whether or not a


Recordset object supports a specific type of functionality

Update

Saves all changes made to a single record in a Recordset


object

UpdateBatch

Saves all changes in a Recordset to the database. Used


when working in batch update mode

Events
Note: You cannot handle events using VBScript or JScript (only Visual Basic,
Visual C++, and Visual J++ languages can handle events).
Event

Description

EndOfRecordset

Triggered when you try to move to a record after the last


record

FetchComplete

Triggered after all records in an asynchronous operation


have been fetched

FetchProgress

Triggered periodically in an asynchronous operation, to


state how many more records that have been fetched

FieldChangeComplete

Triggered after the value of a Field object change

MoveComplete

Triggered after the current position in the Recordset has


changed

RecordChangeComplete

Triggered after a record has changed

RecordsetChangeComplete

Triggered after the Recordset has changed

WillChangeField

Triggered before the value of a Field object change

WillChangeRecord

Triggered before a record change

WillChangeRecordset

Triggered before a Recordset change

WillMove

Triggered before the current position in the Recordset


changes

Collections
Collection

Description

165

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

Fields

Indicates the number of Field objects in the Recordset


object

Properties

Contains all the Property objects in the Recordset object

The Fields Collection's Properties


Property
Count

Description
Returns the number of items in the fields collection.
Starts at zero.
Example:
countfields = rs.Fields.Count

Item(named_item/number)

Returns a specified item in the fields collection.


Example:
itemfields = rs.Fields.Item(1)
or
itemfields = rs.Fields.Item("Name")

The Properties Collection's Properties


Property
Count

Description
Returns the number of items in the properties collection.
Starts at zero.
Example:
countprop = rs.Properties.Count

Item(named_item/number)

Returns a specified item in the properties collection.


Example:
itemprop = rs.Properties.Item(1)
or
itemprop = rs.Properties.Item("Name")

Examples
<html>
<body>
<%
set conn=Server.CreateObject("ADODB.Connection")
conn.Provider="Microsoft.Jet.OLEDB.4.0"
conn.Open(Server.Mappath("/db/northwind.mdb"))

166

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

set rs = Server.CreateObject("ADODB.recordset")
rs.Open "Select * from Customers", conn
'The first number indicates how many records to copy
'The second number indicates what recordnumber to start on
p=rs.GetRows(2,0)
response.write("<p>This example returns the value of the first
column in the first two records:</p>")
response.write(p(0,0))
response.write("<br>")
response.write(p(0,1))
response.write("<p>This example returns the value of the first
three columns in the first record:</p>")
response.write(p(0,0))
response.write("<br>")
response.write(p(1,0))
response.write("<br>")
response.write(p(2,0))
rs.close
conn.close
%>
</body>
</html>

ADO Add Records


We may use the SQL INSERT INTO command to add a record to a table in a
database.

Add a Record to a Table in a Database


We want to add a new record to the Customers table in the Northwind database.
We first create a form that contains the fields we want to collect data from:
<html>
<body>
<form method="post" action="demo_add.asp">
<table>
<tr>
<td>CustomerID:</td>
167

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

<td><input name="custid"></td>
</tr><tr>
<td>Company Name:</td>
<td><input name="compname"></td>
</tr><tr>
<td>Contact Name:</td>
<td><input name="contname"></td>
</tr><tr>
<td>Address:</td>
<td><input name="address"></td>
</tr><tr>
<td>City:</td>
<td><input name="city"></td>
</tr><tr>
<td>Postal Code:</td>
<td><input name="postcode"></td>
</tr><tr>
<td>Country:</td>
<td><input name="country"></td>
</tr>
</table>
<br /><br />
<input type="submit" value="Add New">
<input type="reset" value="Cancel">
</form>
</body>
</html>
When the user presses the submit button the form is sent to a file called
"demo_add.asp". The "demo_add.asp" file contains the code that will add a new
record to the Customers table:
<html>
<body>
<%
set conn=Server.CreateObject("ADODB.Connection")
conn.Provider="Microsoft.Jet.OLEDB.4.0"
conn.Open "c:/webdata/northwind.mdb"
sql="INSERT INTO customers (customerID,companyname,"
sql=sql & "contactname,address,city,postalcode,country)"
sql=sql & " VALUES "
sql=sql & "('" & Request.Form("custid") & "',"
sql=sql & "'" & Request.Form("compname") & "',"
sql=sql & "'" & Request.Form("contname") & "',"
sql=sql & "'" & Request.Form("address") & "',"
sql=sql & "'" & Request.Form("city") & "',"

168

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

sql=sql & "'" & Request.Form("postcode") & "',"


sql=sql & "'" & Request.Form("country") & "')"
on error resume next
conn.Execute sql,recaffected
if err<>0 then
Response.Write("No update permissions!")
else
Response.Write("<h3>" & recaffected & " record
added</h3>")
end if
conn.close
%>
</body>
</html>
Important
If you use the SQL INSERT command be aware of the following:
If the table contains a primary key, make sure to append a unique, non-Null
value to the primary key field (if not, the provider may not append the
record, or an error occurs)
If the table contains an AutoNumber field, do not include this field in the
SQL INSERT command (the value of this field will be taken care of
automatically by the provider)
What about Fields With no Data?
In a MS Access database, you can enter zero-length strings ("") in Text, Hyperlink,
and Memo fields IF you set the AllowZeroLength property to Yes.
Note: Not all databases support zero-length strings and may cause an error when a
record with blank fields is added. It is important to check what data types your
database supports.

ADO Update Records


We may use the SQL UPDATE command to update a record in a table in a
database.

Update a Record in a Table


We want to update a record in the Customers table in the Northwind database. We
first create a table that lists all records in the Customers table:
<html>
169

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

<body>
<%
set conn=Server.CreateObject("ADODB.Connection")
conn.Provider="Microsoft.Jet.OLEDB.4.0"
conn.Open "c:/webdata/northwind.mdb"
set rs=Server.CreateObject("ADODB.Recordset")
rs.open "SELECT * FROM customers",conn
%>
<h2>List Database</h2>
<table border="1" width="100%">
<tr>
<%
for each x in rs.Fields
response.write("<th>" & ucase(x.name) & "</th>")
next
%>
</tr>
<% do until rs.EOF %>
<tr>
<form method="post" action="demo_update.asp">
<%
for each x in rs.Fields
if lcase(x.name)="customerid" then%>
<td>
<input type="submit" name="customerID" value="<
%=x.value%>">
</td>
<%else%>
<td><%Response.Write(x.value)%></td>
<%end if
next
%>
</form>
<%rs.MoveNext%>
</tr>
<%
loop
conn.close
%>
</table>
</body>
</html>
If the user clicks on the button in the "customerID" column he or she will be taken
to a new file called "demo_update.asp". The "demo_update.asp" file contains the
source code on how to create input fields based on the fields from one record in
170

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

the database table. It also contains a "Update record" button that will save your
changes:
<html>
<body>
<h2>Update Record</h2>
<%
set conn=Server.CreateObject("ADODB.Connection")
conn.Provider="Microsoft.Jet.OLEDB.4.0"
conn.Open "c:/webdata/northwind.mdb"
cid=Request.Form("customerID")
if Request.form("companyname")="" then
set rs=Server.CreateObject("ADODB.Recordset")
rs.open "SELECT * FROM customers WHERE customerID='" &
cid & "'",conn
%>
<form method="post" action="demo_update.asp">
<table>
<%for each x in rs.Fields%>
<tr>
<td><%=x.name%></td>
<td><input name="<%=x.name%>" value="<%=x.value%>"></td>
<%next%>
</tr>
</table>
<br /><br />
<input type="submit" value="Update record">
</form>
<%
else
sql="UPDATE customers SET "
sql=sql & "companyname='" & Request.Form("companyname") &
"',"
sql=sql & "contactname='" & Request.Form("contactname") &
"',"
sql=sql & "address='" & Request.Form("address") & "',"
sql=sql & "city='" & Request.Form("city") & "',"
sql=sql & "postalcode='" & Request.Form("postalcode") &
"',"
sql=sql & "country='" & Request.Form("country") & "'"
sql=sql & " WHERE customerID='" & cid & "'"
on error resume next
conn.Execute sql
if err<>0 then
response.write("No update permissions!")
else
171

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

response.write("Record " & cid & " was updated!")


end if
end if
conn.close
%>
</body>
</html>

ADO Delete Records


We may use the SQL DELETE command to delete a record in a table in a
database.

Delete a Record in a Table


We want to delete a record in the Customers table in the Northwind database. We
first create a table that lists all records in the Customers table:
<html>
<body>
<%
set conn=Server.CreateObject("ADODB.Connection")
conn.Provider="Microsoft.Jet.OLEDB.4.0"
conn.Open "c:/webdata/northwind.mdb"
set rs=Server.CreateObject("ADODB.Recordset")
rs.open "SELECT * FROM customers",conn
%>
<h2>List Database</h2>
<table border="1" width="100%">
<tr>
<%
for each x in rs.Fields
response.write("<th>" & ucase(x.name) & "</th>")
next
%>
</tr>
<% do until rs.EOF %>
<tr>
<form method="post" action="demo_delete.asp">
<%
for each x in rs.Fields
if x.name="customerID" then%>
<td>
<input type="submit" name="customerID" value="<
%=x.value%>">

172

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

</td>
<%else%>
<td><%Response.Write(x.value)%></td>
<%end if
next
%>
</form>
<%rs.MoveNext%>
</tr>
<%
loop
conn.close
%>
</table>
</body>
</html>
If the user clicks on the button in the "customerID" column he or she will be taken
to a new file called "demo_delete.asp". The "demo_delete.asp" file contains the
source code on how to create input fields based on the fields from one record in
the database table. It also contains a "Delete record" button that will delete the
current record:
<html>
<body>
<h2>Delete Record</h2>
<%
set conn=Server.CreateObject("ADODB.Connection")
conn.Provider="Microsoft.Jet.OLEDB.4.0"
conn.Open "c:/webdata/northwind.mdb"
cid=Request.Form("customerID")
if Request.form("companyname")="" then
set rs=Server.CreateObject("ADODB.Recordset")
rs.open "SELECT * FROM customers WHERE customerID='" &
cid & "'",conn
%>
<form method="post" action="demo_delete.asp">
<table>
<%for each x in rs.Fields%>
<tr>
<td><%=x.name%></td>
<td><input name="<%=x.name%>" value="<%=x.value%>"></td>
<%next%>
</tr>
</table>
<br /><br />

173

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

<input type="submit" value="Delete record">


</form>

<%
else
sql="DELETE FROM customers"
sql=sql & " WHERE customerID='" & cid & "'"
on error resume next
conn.Execute sql
if err<>0 then
response.write("No update permissions!")
else
response.write("Record " & cid & " was deleted!")
end if
end if
conn.close
%>
</body>
Display the Records
<html>
<body>
<%
set conn=Server.CreateObject("ADODB.Connection")
conn.Provider="Microsoft.Jet.OLEDB.4.0"
conn.Open(Server.Mappath("/db/northwind.mdb"))
set rs = Server.CreateObject("ADODB.recordset")
rs.Open "Select * from Customers", conn
do until rs.EOF
for each x in rs.Fields
Response.Write(x.name)
Response.Write(" = ")
Response.Write(x.value & "<br />")
next
Response.Write("<br />")
rs.MoveNext
loop
rs.close
conn.close
%>
</body>

174

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

</html>

Display the records in HTML table


<html>
<body>
<%
set conn=Server.CreateObject("ADODB.Connection")
conn.Provider="Microsoft.Jet.OLEDB.4.0"
conn.Open(Server.Mappath("/db/northwind.mdb"))
set rs = Server.CreateObject("ADODB.recordset")
rs.Open "SELECT Companyname, Contactname FROM
Customers", conn
%>
<table border="1" width="100%">
<%do until rs.EOF%>
<tr>
<%for each x in rs.Fields%>
<td><%Response.Write(x.value)%></td>
<%next
rs.MoveNext%>
</tr>
<%loop
rs.close
conn.close
%>
</table>
</body>
</html>

175

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

Components
ASP AdRotator Component
The ASP AdRotator component creates an AdRotator object that displays a
different image each time a user enters or refreshes a page. A text file includes
information about the images.
Syntax
<%
set adrotator=server.createobject("MSWC.AdRotator")
adrotator.GetAdvertisement("textfile.txt")
%>
Example
Assume we have a file called "banners.asp". It looks like this:
<html>
<body>
<%
set adrotator=Server.CreateObject("MSWC.AdRotator")
response.write(adrotator.GetAdvertisement("ads.txt"))
%>
</body>
</html>
The file "ads.txt" looks like this:
*
w3schools.gif
http://www.w3schools.com/
Visit W3Schools
80
microsoft.gif
http://www.microsoft.com/
Visit Microsoft
20
The lines below the asterisk in the file "ads.txt" specifies the images to be
displayed, the hyperlink addresses, the alternate text (for the images), and the
display rates in percent of the hits. We see that the W3Schools image will be

176

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

displayed for 80 % of the hits and the Microsoft image will be displayed for 20 %
of the hits in the text file above.
Note: To get the links to work when a user clicks on them, we will have to modify
the file "ads.txt" a bit:
REDIRECT banners.asp
*
w3schools.gif
http://www.w3schools.com/
Visit W3Schools
80
microsoft.gif
http://www.microsoft.com/
Visit Microsoft
20
The redirection page (banners.asp) will now receive a querystring with a variable
named URL containing the URL to redirect to.
Note: To specify the height, width, and border of the image, you can insert the
following lines under REDIRECT:
REDIRECT banners.asp
WIDTH 468
HEIGHT 60
BORDER 0
*
w3schools.gif
...
...
The last thing to do is to add some lines of code to the "banners.asp" file:
<%
url=Request.QueryString("url")
If url<>"" then Response.Redirect(url)
%>
<html>
<body>
<%
set adrotator=Server.CreateObject("MSWC.AdRotator")
response.write(adrotator.GetAdvertisement("textfile.txt"))
%>
</body>
</html>

177

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

That's all!!
Properties
Property

Description

Example

Border

<%
set
adrot=Server.CreateObject("MSWC.AdRotator"
Specifies the size of
)
the borders around
adrot.Border="2"
the advertisement
Response.Write(adrot.GetAdvertisement("ads.tx
t"))
%>

Clickable

<%
set
adrot=Server.CreateObject("MSWC.AdRotator"
Specifies whether the
)
advertisement is a
adrot.Clickable=false
hyperlink
Response.Write(adrot.GetAdvertisement("ads.tx
t"))
%>

TargetFrame

Name of the frame to <%


display the
set
advertisement
adrot=Server.CreateObject("MSWC.AdRotator"
)
adrot.TargetFrame="target='_blank'"
Response.Write(adrot.GetAdvertisement("ads.tx
t"))
%>

Methods
Method

GetAdvertisement

Description

Example

<%
set
Returns HTML
adrot=Server.CreateObject("MSWC.AdRotator"
that displays the
)
advertisement in
Response.Write(adrot.GetAdvertisement("ads.tx
the page
t"))
%>

178

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

Examples
Simple AdRotator Example
This example shows how to use the AdRotator component to display a different
advertisement image, each time a user visits or refreshes the page.
<html>
<body>
<%
set adrotator=Server.CreateObject("MSWC.AdRotator")
adrotator.Border="2"
Response.Write(adrotator.GetAdvertisement("text/advertisement
s.txt"))
%>
<p>
NOTE: Because images are changed randomly, and because this
page has few images to choose from, it will often display the
same advertisement twice in a row.
</p>
<p>
<a href="text/advertisements.txt">
<img border="0" src="/images/btn_view_text.gif">
</a>
</p>
</body>
</html>

ASP Browser Capabilities Component


The ASP Browser Capabilities component creates a BrowserType object that
determines the type, capabilities and version number of each browser that visits
your site.
When a browser connects to a server, an HTTP User Agent Header is also sent to
the server. This header contains information about the browser (like browser type
and version number). The BrowserType object then compares the information in
the header with information in a file on the server called "Browscap.ini".
If there is a match between the browser type and version number sent in the header
and the information in the "Browsercap.ini" file, you can use the BrowserType
object to list the properties of the matching browser. If there is no match for the
browser type and version number in the Browscap.ini file, it will set every
property to "UNKNOWN".

179

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

Syntax
<%
Set MyBrow=Server.CreateObject("MSWC.BrowserType")
%>
The example below creates a BrowserType object in an ASP file, and displays a
table showing some of the capabilities of the current browser:
<html>
<body>
<%
Set MyBrow=Server.CreateObject("MSWC.BrowserType")
%>
<table border="1" width="100%">
<tr>
<th>Client OS</th>
<th><%=MyBrow.platform%></th>
</tr><tr>
<td >Web Browser</td>
<td ><%=MyBrow.browser%></td>
</tr><tr>
<td>Browser version</td>
<td><%=MyBrow.version%></td>
</tr><tr>
<td>Frame support?</td>
<td><%=MyBrow.frames%></td>
</tr><tr>
<td>Table support?</td>
<td><%=MyBrow.tables%></td>
</tr><tr>
<td>Sound support?</td>
<td><%=MyBrow.backgroundsounds%></td>
</tr><tr>
<td>Cookies support?</td>
<td><%=MyBrow.cookies%></td>
</tr><tr>
<td>VBScript support?</td>
<td><%=MyBrow.vbscript%></td>
</tr><tr>
<td>JavaScript support?</td>
<td><%=MyBrow.javascript%></td>
</tr>
</table>
</body>
</html>

180

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

Output:
Client OS

WinNT

Web Browser

IE

Browser version

5.0

Frame support?

True

Table support?

True

Sound support?

True

Cookies support?

True

VBScript support?

True

JavaScript support?

True

The Browscap.ini File


The "Browsercap.ini" file is used to declare properties and to set default values for
browsers.
This section is not a tutorial on how to maintain "Browsercap.ini" files, it only
shows you the basics; so you get an idea what a "Browsercap.ini" file is all about.
The "Browsercap.ini" file can contain the following:
[;comments]
[HTTPUserAgentHeader]
[parent=browserDefinition]
[property1=value1]
[propertyN=valueN]
[Default Browser Capability Settings]
[defaultProperty1=defaultValue1]
[defaultPropertyN=defaultValueN]
Parameter
comments

Description
Optional. Any line that starts with a semicolon are ignored by the
BrowserType object

Optional. Specifies the HTTP User Agent header to associate with the
HTTPUserA
browser-property value statements specified in propertyN. Wildcard
gentHeader
characters are allowed
browserDefi Optional. Specifies the HTTP User Agent header-string of a browser to use
nition
as the parent browser. The current browser's definition will inherit all of
181

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

the property values declared in the parent browser's definition


Optional. Specifies the browser properties. The following table lists some
possible properties:
ActiveXControls - Support ActiveX controls?
Backgroundsounds - Support background sounds?
Cdf - Support Channel Definition Format for Webcasting?
Tables - Support tables?
Cookies - Support cookies?
propertyN

Frames - Support frames?


Javaapplets - Support Java applets?
Javascript - Supports JScript?
Vbscript - Supports VBScript?
Browser - Specifies the name of the browser
Beta - Is the browser beta software?
Platform - Specifies the platform that the browser runs on
Version - Specifies the version number of the browser

valueN

Optional. Specifies the value of propertyN. Can be a string, an integer


(prefix with #), or a Boolean value

Optional. Specifies the name of the browser property to which to assign a


defaultPrope
default value if none of the defined HTTPUserAgentHeader values match
rtyN
the HTTP User Agent header sent by the browser
defaultValue Optional. Specifies the value of defaultPropertyN. Can be a string, an
N
integer (prefix with #), or a Boolean value
A "Browsercap.ini" file might look something like this:
;IE 5.0
[IE 5.0]
browser=IE
Version=5.0
majorver=#5
minorver=#0
frames=TRUE
tables=TRUE
cookies=TRUE
backgroundsounds=TRUE

182

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

vbscript=TRUE
javascript=TRUE
javaapplets=TRUE
ActiveXControls=TRUE
beta=False
;DEFAULT BROWSER
[*]
browser=Default
frames=FALSE
tables=TRUE
cookies=FALSE
backgroundsounds=FALSE
vbscript=FALSE
javascript=FALSE
Examples
<html>
<body>
<%
Set MyBrow=Server.CreateObject("MSWC.BrowserType")
%>
<table border="1" width="65%">
<tr>
<td width="52%">Client OS</td>
<td width="48%"><%=MyBrow.platform%></td>
</tr>
<tr>
<td >Web Browser</td>
<td ><%=MyBrow.browser%></td>
</tr>
<tr>
<td>Browser version</td>
<td><%=MyBrow.version%></td>
</tr>
<tr>
<td>Frame support?</td>
<td><%=MyBrow.frames%></td>
</tr>
<tr>
<td>Table support?</td>
<td><%=MyBrow.tables%></td>
</tr>
<tr>
183

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

<td>Sound support?</td>
<td><%=MyBrow.backgroundsounds%></td>
</tr>
<tr>
<td>Cookies support?</td>
<td><%=MyBrow.cookies%></td>
</tr>
<tr>
<td>VBScript support?</td>
<td><%=MyBrow.vbscript%></td>
</tr>
<tr>
<td>JavaScript support?</td>
<td><%=MyBrow.javascript%></td>
</tr>
</table>
</body>
</html>

ASP Content Linking Component


The ASP Content Linking component is used to create a quick and easy navigation
system!
The Content Linking component returns a Nextlink object that is used to hold a list
of Web pages to be navigated.
Syntax
<%
Set nl=Server.CreateObject( "MSWC.NextLink" )
%>
First we create a text file - "links.txt". This file contains the pages to be navigated.
The pages must be listed in the same order you want them to be displayed, and it
also must contain a description for each file name (use the tab key to separate file
name from description). Note: If you want to add a page to the list or change the
order of the pages in the list; all you have to do is to modify the text file! The
navigation will automatically be correct!
"links.txt":
asp_intro.asp ASP Intro
asp_syntax.asp ASP Syntax
asp_variables.asp ASP Variables
asp_procedures.asp ASP Procedures
On each of the pages listed above, put one line of code: <!-- #include
184

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

file="nlcode.inc"-->. This line will include the code below on every page listed in
"links.txt" and the navigation will work.
"nlcode.inc":
<%
'Use the Content Linking Component
'to navigate between the pages listed
'in links.txt
dim nl
Set nl=Server.CreateObject("MSWC.NextLink")
if (nl.GetListIndex("links.txt")>1) then
Response.Write("<a href='" &
nl.GetPreviousURL("links.txt"))
Response.Write("'>Previous Page</a>")
end if
Response.Write("<a href='" & nl.GetNextURL("links.txt"))
Response.Write("'>Next Page</a>")
%>
The ASP Content Linking Component's methods are described below:
Methods
Met
hod

Description

Example

<%
dim nl,c
Set
nl=Server.CreateObject("MSWC.NextLink"
)
Get
List Returns the number of items listed in c=nl.GetListCount("links.txt")
Response.Write("There are ")
Cou the Content Linking List file
Response.Write(c)
nt
Response.Write(" items in the list")
%>
Output:
There are 4 items in the list
Get Returns the index number of the
ListI current item in the Content Linking
ndex List file. The index number of the
first item is 1. 0 is returned if the
current page is not in the Content
Linking List file

185

<%
dim nl,c
Set
nl=Server.CreateObject("MSWC.NextLink"
)
c=nl.GetListIndex("links.txt")
Response.Write("Item number ")

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

Response.Write(c)
%>
Output:
Item number 3

Get
Next
Desc
ripti
on

Returns the text description of the


next item listed in the Content
Linking List file. If the current page
is not found in the list file it returns
the text description of the last page
on the list

<%
dim nl,c
Set
nl=Server.CreateObject("MSWC.NextLink"
)
c=nl.GetNextDescription("links.txt")
Response.Write("Next ")
Response.Write("description is: ")
Response.Write(c)
%>
Next description is: ASP Variables

<%
dim nl,c
Set
nl=Server.CreateObject("MSWC.NextLink"
Returns the URL of the next item
Get listed in the Content Linking List file. )
Next If the current page is not found in the c=nl.GetNextURL("links.txt")
URL list file it returns the URL of the last Response.Write("Next ")
Response.Write("URL is: ")
page on the list
Response.Write(c)
%>
Next URL is: asp_variables.asp

Get
Nth Returns the description of the Nth
Desc page listed in the Content Linking
ripti List file
on

<%
dim nl,c
Set
nl=Server.CreateObject("MSWC.NextLink"
)
c=nl.GetNthDescription("links.txt",3)
Response.Write("Third ")
Response.Write("description is: ")
Response.Write(c)
%>
Third description is: ASP Variables

Get Returns the URL of the Nth page


<%
Nth listed in the Content Linking List file dim nl,c
URL
Set
186

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

nl=Server.CreateObject("MSWC.NextLink"
)
c=nl.GetNthURL("links.txt",3)
Response.Write("Third ")
Response.Write("URL is: ")
Response.Write(c)
%>
Third URL is: asp_variables.asp

GetP
revi
ous
Desc
ripti
on

Returns the text description of the


previous item listed in the Content
Linking List file. If the current page
is not found in the list file it returns
the text description of the first page
on the list

<%
dim nl,c
Set
nl=Server.CreateObject("MSWC.NextLink"
)
c=nl.GetPreviousDescription("links.txt")
Response.Write("Previous ")
Response.Write("description is: ")
Response.Write(c)
%>
Previous description is: ASP Variables

Returns the URL of the previous item


GetP
listed in the Content Linking List file.
revi
If the current page is not found in the
ous
list file it returns the URL of the first
URL
page on the list

<%
dim nl,c
Set
nl=Server.CreateObject("MSWC.NextLink"
)
c=nl.GetPreviousURL("links.txt")
Response.Write("Previous ")
Response.Write("URL is: ")
Response.Write(c)
%>
Previous URL is: asp_variables.asp

Example
<html>
<body>
<p>
The example below builds a table of contents.
</p>
<%

187

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

dim c
dim i
set nl=server.createobject("MSWC.Nextlink")
c = nl.GetListCount("text\links.txt")
i=1
%>
<ul>
<%do while (i <= c) %>
<li><a href="<%=nl.GetNthURL("text\links.txt", i)%>">
<%=nl.GetNthDescription("text\links.txt", i)%></a>
<%
i = (i + 1)
loop
%>
</ul>
<p>
The text file contains a list of page urls
and link descriptions. It contains one line of text for each page.
Note that the url and
description MUST be separated by the TAB character.
</p>
<p>
<a href="text/links.txt"><img border="0"
src="/images/btn_view_text.gif"></a>
</p>
</body>

Output Result:
The example below builds a table of contents.
ASP Intro
ASP Syntax
ASP Variables
ASP Procedures
The text file contains a list of page urls and link descriptions. It contains one line
of text for each page. Note that the url and description MUST be separated by the
TAB character.
Text file content

188

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

asp_intro.asp
ASP
asp_syntax.asp
ASP
asp_variables.asp ASP
asp_procedures.asp ASP

Intro
Syntax
Variables
Procedures

ASP Content Rotator Component


The ASP Content Rotator component creates a ContentRotator object that displays
a different HTML content string each time a user enters or refreshes a page. A text
file, called the Content Schedule File, includes the information about the content
strings.
The content strings can contain HTML tags so you can display any type of content
that HTML can represent: text, images, colors, or hyperlinks.
Syntax
<%
Set cr=Server.CreateObject( "MSWC.ContentRotator" )
%>
The following example displays a different content each time a user views the Web
page. Create a text file named "textads.txt" in your default Web Site folder, in a
subfolder called text.

"textads.txt":
%% #1
This is a great day!!
%% #2
<h1>Smile</h1>
%% #3
<img src="smiley.gif">
%% #4
Here's a <a href="http://www.w3schools.com">link.</a>
Notice the #number at the beginning of each content string. This number is an

189

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY

optional parameter that indicates the relative weight of the HTML content string.
In this example, the Content Rotator will display the first content string one-tenth
of the time, the second string two-tenths of the time, the third string three-tenths of
the time, and the fourth string four-tenths of the time.
Then, create an ASP file, and insert the following code:
<html>
<body>
<%
set cr=server.createobject("MSWC.ContentRotator")
response.write(cr.ChooseContent("text/textads.txt"))
%>
</body>
</html>

The ASP Content Rotator Component's methods are described below:


Methods
Method

Description

Example

ChooseCont Gets and displays a content


ent
string

<%
dim cr
Set
cr=Server.CreateObject("MSWC.ContentR
otator")
response.write(cr.ChooseContent("text/text
ads.txt"))
%>
Output:

190

By R.Senthil Kumar MCA.,ME.,RGCET

INTERNET PROGRAMMING AND WEB TECHNOLOGY


S

ile y

Here's a link.

191

By R.Senthil Kumar MCA.,ME.,RGCET

También podría gustarte