Introduction
· Cautions
· N-tier server architecture
· Client-side pages
· Server-side pages
Server Logs
· Analysis of the logs
· Links for log information
ASP introduction
· ASP script example
· Client VBScript
· Server VBScript
· Checkpoint
· What happens next?
· VBScript vs. JavaScript
· Server-Side vs. Client-Side
· Client-side scripts
· Server-side scripts
· Checkpoint
PHP introduction
· PHP script example
Hypertext transfer protocol
· HTTP request/response
· HTTP transfer diagram
· The request line
· The HTTP header
· The HTTP Body
· The response line
· The HTTP Header
· The HTTP Body
· Major HTTP elements
· Checkpoint
Server-side includes
· *.SHTML
· ASP Includes
· PHP includes
Sending form data
· ASP and forms
· PHP and forms
· Sending other data
· Inspecting what is sent
· Example of Radio Buttons
· Example of Check Boxes
· Example of Select List
· Text Box Example
· TextArea Example
· Textarea Warning:
· Checkboxes with same name
· Checkboxes with diff names
· Form controls in arrays
Redirecting to other scripts
· Redirecting visitors with ASP
· Redirecting visitors with PHP
Advantages of server-scripting
· Visitor information
· Where visitor linked from
· IP address and host
· Browser and operating system
· HTTP scripts: ASP
· HTTP scripts: PHP
Web services
· XML carries services
· Locating a Web Service
Mastery test
Top of page
References
W3Schools Intro to ASP
W3Schools ASP Syntax
ASP 101 Examples
4 Guys from Rolla ASP Tips
O'Reilly PHP
PHP FAQ
Navigation

41. Server introduction

Introduction  (click any heading below to return here)

Up to this point in the course you have designed and authored client-side Web pages using XHTML, CSS, XML and Javascript. You have been editing and running Web pages on your client workstation without being required to connect to the Internet. The client-side has been nearly sufficient to this point and Web servers have been used only to hold your pages for world wide access.

Although server-side programming has not been your concern until now, it is crucial to successfully deploying up-to-date Web projects. Server scripts were developed specifically to bolster dynamic page production and to improve Web access to databases. The list below summarizes how we benefit from server-side application.

  • common data files
  • fresh content (see "news stories" later)
  • visitor characteristics (see "access logs" later)
  • hiding code logic
  • shared code/source libraries
  • protection with passwords
  • protection with SSL security
  • scalable architecture (growth potential)
  • longer system lifespan
  • Web services connections


Cautions

In this lesson you will learn about popular server software. It is important to understand that not all Web servers and their software are alike. If you already have a Host, find out what is installed by e-mailing the webmaster. Your server may or may not have the software packages introduced in this lesson.

If you are shopping for a Host, read about pricing levels and packages that are available. You will find many Hosts providing extremely powerful options to do everything introduced here and much more.

Finally, exact versions and installed options will affect your server solutions. This is analogous to the first lesson in this course where you learned about the five Internet Explorer options available to you. Just as you can fine tune your client-side browser, the webmaster can fine tune his or her server-side software array.


N-tier server architecture

If you have been following the sequence of the course, you know how to create client-side XHTML pages. And if you have been uploading the pages to a Web server, then you have been using a 2-tier system architecture: a client and a server.

An N-tiered architecture uses multiple servers to process Web requests instead of having one server handle all the requests (whether for static pages, Active Server Pages, Java Beans, Images, Oracle database, an so on).

The advantage to developers is that the servers are independent of each other. Therefore, if the image server goes down, it does not affect the database server. Hence, the images may not appear on webpages, but the webpages that require database functionality will still run. A second advantage of a tiered model architecture is that it allows requests to run quicker and more smoothly. If only one server handled all requests then bottlenecks could result.

The advantages of N-tier system design are:

  • Business logic modification without changes to interface or db
  • A better load balance
  • Increased throughput
  • Business logic objects can be used by multiple Web applications
  • Isolates the knowledge required for any given tier (security)

An offshoot of the tiered model is the territorial (turf wars) nature of business environments. The disadvantages or side-effect of a tiered architecture is the coordination complexity at times. For example, for testing purposes,multi-tiered architecture requires more work for quality control. Other disadvantages are:

  • System design and Web application design is more complex
  • Tiered architectures are harder to maintain and test
  • Costs are increased


Client-side pages

Client-side pages are static because they cannot read from a database, so only the content that you last marked up will appear. When someone on the Web wishes to see a static page, the following process takes place:

  1. The user enters URL request into browser. This request is passed to the Web server over the Internet.
  2. The server locates the static XHTML page.
  3. The server sends the page back to the browser.
  4. The browser decodes the XHTML, then formats and displays the Web page.
Static Web pages


Server-side pages

A dynamic server page is one generated on request by a program written in a server scripting language. Instead of simply writing an XHTML document, you may code a set of scripting instructions (a program) that will be used to create XHTML pages. In other words, you will write a program that will in turn mark up an XHTML page. The program will be run on the server before the page is sent to the browser. These are the steps involved in accessing dynamic server pages:

  1. The user enters a URL request into the browser, and it is passed to the Web server over the Internet.
  2. The server locates the file of instructions (the script).
  3. The server follows these instructions and creates an XHTML document.
  4. This newly created XHTML document is sent to the browser.
  5. The browser decodes the XHTML, then formats and displays the Web page.

Server Logs

When we request HTML and ASP pages from Web servers, the server can record information in its files about the requests. These files are called access logs or server logs.

There are about four popular free server log analyzers (Analog, AWState, WebAlizer, and HitBox). They are compared by SourceForge to help understand how features compare.

Webmasters have many options about the analyzer they choose and the contents of log files they record. A sample of these options is shown in the list below. Logs are valuable information for answering questions like these:

  • Number of visits
  • Number of unique visitors
  • Last visits
  • Who are the visitors
  • How long do visitors stay
  • Where they go in a site
  • Where visitors came from
  • Keywords used to get to site
  • Operating system used
  • Browser used
  • Screen size
  • Errors that occurred
  • Time of visit
  • Days of week and rush hours
  • Domains/countries of hosts visitors (domains/countries detected)
  • Hosts list, last visits, and unresolved IP addresses list
  • Most viewed, entry, and exit pages
  • File type
  • Visits of robots
  • Search engines, keyphrases, and keywords used to find site
  • HTTP errors (Page Not Found)

Log information falls in four categories, and may be recorded in one to four server files.



Log Types Description and site questions answered by the log information
Agent log Name and version of the user agent (browser) requesting a page. Do you need to support many customers running Opera or Netscape 4?
Referrer log URL of the page before requesting a page. Which Web sites are providing you with valuable traffic?
Transfer log Time of the request. How long do users stay on my pages?
Error log Requests my pages could not handle. Are there dead links on my pages?



Analysis of the logs

The site questions above can be answered by statistical analysis of the logs. The access logs format is very cluttered and wordy, making them unusable for visual analysis, so we rely on computer programming once again. Here is a very popular shareware analyzer, called Analog


Links for log information

ASP introduction

The ASP technology interprets your instructions for generating dynamic XHTML markup. ASP is a suite of server-side technologies (not a language) that allows your pages to be constructed on the server just before they are sent to the browser. It helps you mix programming logic with XHTML markup.

Your ASP pages will consist of XHTML tags and content, as usual. In addition you can insert new scripting code inside ASP tags:

<% VBScript code %>

Going back to the client/server process again, when a page request is sent to the server it checks the file extension. If the file has an .html extension, the server will assume that the page is a static XHTML page. If the file has a .asp extension, then the server knows that it is an ASP file that contains server instructions.

The script code you write may read cookies or databases, locate and assemble fresh content (i.e., current news stories), send e-mail, and customize the XHTML sent to the browser. The markup received at the browser looks like common XHTML, but it is dynamically written.


ASP script example

Both client and server scripts need to write XHTML. You learned to write client scripts that write XHTML when you studied JavaScript. Here are VBScript examples that introduce an important DOM syntax difference between clients and servers.


Client VBScript

Client scripts use the document object to write XHTML.


<script language="VBScript" type="text/vbscript">
    document.write("<p>Written by a client script</p>")
</script>


Server VBScript

Server scripts use the response object to write XHTML.


<%
    response.write("<p>Written by a server script</p>")
%>

There is an introduction to ASP and example scripts in a later lesson.


Checkpoint    (answer then click)

You have entered a URL and file name of a Web page in the address bar. How will the Web server process differ if the page you are accessing is a server script?


What happens next?

Once the server recognizes the ASP extension, it then goes through the process of dynamically creating the XHTML to send back to the browser. It accomplishes this task by going through the different 'nuggets' of programming code that will be embedded within the XHTML. This code (located within the ASP delimiters) will be found in the form of scripting languages.

<%@ Language=VBScript  %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en-US">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Simple ASP Example </title>
</head>
<body>
<h1>The following is written through ASP technology:</h1>

<%  response.write("<p>This was written by VBScript</p>")  %>

</body></html>

If this file is saved with a .asp extension, then the server will assume it is ASP and will read it. The first line it encounters is:

<%@ Language=VBScript %>

This line tells the server that the scripting language being used in this particular ASP file is VBScript. The next point at which the server will stop to process code is at:

<%  response.write("<p>This was written by VBScript</p>") %>

Here, the VBScript code processed by the ASP engine will result in a simple paragraph container sent back to the client as valid XHTML.


VBScript vs. JavaScript

In the previous example, the scripting language used was VBScript. VBScript is the most commonly used ASP scripting language. We could use JavaScript, but for our purposes, VBScript will be the language of choice.


Server-Side vs. Client-Side

Something that many people get confused about is the distinction between server-side scripting and client-side scripting. When the server comes across a script, it must identify which machine is responsible for the processing. ASP is solely a server-side technology but scripting languages can be used at both sides of the operation.

Client JavaScripts and VBScripts must be distinguished from ASP scripts by using a <script> container instead of the <% %> ASP container.

<script language="VBScript" type="text/vbscript">
    Some client-side VBScript logic
</script>


Client-side scripts

The <script> tags can be embedded in a document with either .asp or .html extensions. When the server reads the document, it will return the scripted portion of the file untouched to be read and processed by the browser. This process is known as client-side scripting, since it is the client (browser) that interprets the scripting language, not the server.


Server-side scripts

Scripting within a <% %> container will be considered ASP and will be processed on the Web server. Remember that anything in the ASP container will only be executed if the file is named with a .asp extension. For files named with .html extension, it is only possible to use the <script> tags - and then the scripts will be interpreted as non-ASP scripts (client scripts).

There is one exception that is not a recommended practice. You can include the runat="server" attribute within <script> to signal processing on the server. A better practice is to use the ASP container <% %> instead.

<script runat="server" language="VBScript" type="text/vbscript">
    Some server-side VBScript logic
</script>


Checkpoint    (answer then click)

What is the difference between server-side and client-side scripting? What is the proper syntax for each? Click the check point to confirm your answers.

PHP introduction

Like the ASP suite of technologies, PHP is another popular scripting tool. It allows Web pages to be constructed on the server just before they are sent to the browser.

PHP pages will usually consist of XHTML tags and content. In addition, you can insert new scripting code inside PHP tags:

<?php PHP script code ?>

Going back to the client/server process again, when a page request is sent to the server it checks the file extension. If the file has a .html extension, the server will assume that the page is a static XHTML page. If the file has a .php extension, then the server knows that it is a PHP file that contains instructions.

The script code may read cookies or databases, locate and assemble fresh content (i.e., recent news stories), send e-mail, and customize the XHTML sent to the browser. The markup received at the browser looks like common XHTML, but it is dynamically written.

Summary of PHP features

  • Create charts and graphics (as images) on the fly
  • Create simple Flash animations on the fly
  • Create PDF documents on the fly
  • Leverage advanced math capabilities and object-oriented methodologies
  • Read and write to local and IMAP mailboxes
  • Use standard Internet protocols: FTP, Web, or news client
  • Create a new client and server protocol using standard TCP/IP sockets
  • Implement cryptographic support
  • Connect to database servers (Oracle, SQL Server, Sybase, Access, MySQL)

  • Source: Benefits of PHP by Vincent Danen


PHP script example

Unlike VBScript that can be used on both the client and the server, PHP runs only on servers. There is no client-side syntax to learn. Remember, you must place PHP scripts in server files named with a .php extension for them to run.


<?php
    print ("<p>Written by a server script</p>");
?>

The different nature of these two scripting languages is most evident in case sensitivity and end-of-line punctuation. PHP is case sensitive and requires the semicolon at the end of every statement. VBScript has neither requirement.

There is an introduction to PHP and example scripts in a later lesson.

Hypertext transfer protocol

As you know by now, the Internet is a network of interconnected networks spanning the world and connecting millions of computers. You learned earlier that the TCP/IP networking protocol ensures that packets of information called datagrams flow over the Internet correctly. The Web has operated on the Internet since 1991 because Web browsers and Web servers have agreed to their own "Web protocol" known as the Hypertext Transfer Protocol (HTTP).


HTTP request/response protocol

Most HTTP communication is initiated by browsers. A browser sends a request to a Web server in the form of a request method, URL, and protocol version, followed by a message containing request codes, browser information, and optional body content. The Web server responds with a status code (protocol version and a success/error flag), followed by server information and optional body content. It is the body information that contains the final XHTML page.


HTTP transfer diagram

Information that is passed between the client and the server is information that can be used within ASP scripting. Each HTTP request and response is made up of three main parts: the Request/Response line, the Header and the Body. While the format for both the request and the response are the same, the information relayed is different. We will examine the setup of both the HTTP request and response.

HTTP Transfer Diagram


The request line

The Request line contains the following information:
  1. The Method - Used to tell the server how much information is being sent and how much information is needed from the server. Many different methods are supported by HTTP, but the three most common are GET, HEAD and POST.
    • GET is a request for information located at the given URL on the server, such as an XHTML or ASP page, or graphics. Most HTTP requests are GET.
    • HEAD means you are only requesting the HTML header and no other data.
    • POST means you are sending information for use by the server. An example is information submitted from XHTML forms.
  2. The URL of the requested file
  3. The version number of HTTP


The HTTP header

The header contains details of what type of documents will be accepted by the client, the browser type and the date and time (and the general configuration of the client receiving the information). The information in the header can be in three different categories:

  1. General: information about the client or the server
  2. Entity: information about the data being sent between the client and the server
  3. Request: information about client settings and different types of acceptable information.


The HTTP Body

If POST was used with the XHTML form request, then this segment contains the form data sent to the server. Otherwise, nothing is sent in this part.


The response line

The response line returns two things:

  1. The HTTP version number
  2. Whether or not the transfer was a success


The HTTP Header

The response header has these categories:

  • General: information about the client or the server
  • Entity: information about the data being sent between the client and the server
  • Response: information about the server and specifics about the response


The HTTP Body

With a successful request, the XHTML code on the page will be sent in this part of the Response. Otherwise, this section will contain an error message for the browser. For example, if a page cannot be found, then error 404 is returned.


Major HTTP elements

Here are a few examples that show the major elements in HTTP packets.

HTTP Request HTTP Response
Request Line Response Line
    
    GET/ example.html  HTTP/1.1
    
    
    
    HTTP/1.1/200
    
    
Header Header
    
    Useragent: IE 5.0
    Accept: */*
    Date 7/20/01
    
    
    
    Server: IIS 50
    Date: 7/20/01
    
    
Body Body
(Contains data only when
POST method used in HTTP request)
    <HTML>

    (....HTML markup)

    </HTML>
    



Checkpoint    (answer then click)

What are the main parts that make up HTTP Requests and Responses? What do each of these parts do? Click the checkpoint to confirm your answers.

Server-side includes

A major advantage of server-side scripting is the ability to have reusable source code that can be appended to your XHTML pages. For example, you could write a page footer once and include it automatically on every page. If you have learned to program JavaScript function libraries, then you already know one way to do the same thing on the client side.


*.SHTML

Naming your files *.shtml on some servers that have been configured to accept SSI (server-side includes) will cause the server to open the file and parse it before sending it back in the body of an HTTP packet. By parsing your XHTML, the server logic will look for lines like the one below. When found, the files will be included in line with your XHTML markup.

<!--#include file="footer.inc"-->

SSI may not be available for your server. There are other ways of including reusable markup that are covered next.


ASP Includes

In addition to using JavaScript and SSI to include reusable markup, you may use ASP as well. First, name your main markup file *.asp, since it will be an ASP script. Then, in the file where you want to include other source code, either XHTML or scripts, add a line like the following:

<!--#include file="footer.inc"-->

In the lesson that introduces ASP, you will see many other examples of this practical feature.


PHP includes

You also may include files in your PHP scripts. Here, the assumption is that you will include XHTML markup, not additional PHP scripts, so if you wish to include scripts they must be enclosed in PHP tags. Here are two examples to make this concept clear.

<?php
print "Welcome to Web server authoring";
include("page34.html");
include("footer.php");
?>

The file page34.html would contain only XHTML markup. The file footer.php, on the other hand, must begin and end with the PHP container tags <?php ?>.

Sending form data

Imagine you have an XHTML form that submits a user ID and password to an ASP/PHP program for verification. The XHTML file that sends these values would have the following markup:

<form id="example" method="get" action="verify.asp">
Enter your User ID <input type="text" name="UID" /><br />
And Password <input type="password" name="PSWD" /><br />
<input type="submit" />
</form>


ASP and forms

How do we receive this data into an ASP program? ASP 3.0 and newer versions support a shorthand syntax for requesting form data: request(). For example userID = request("UID"). Previous versions required request.querystring() for data submitted by the get method, and request.form() for data sent by the post method. Instead of these methods, you can now use a single request() method.

You will need to include the names of the data in the request() method. In the above example, you would use the following syntax to code ID and password variables in an ASP program: request("UID") and request("PSWD").


PHP and forms

Like ASP, you can use $_REQUEST[] to retrieve the form data. For example, when it is necessary to acquire HTML form data: $id = $_REQUEST["UID"]. Form data is automatically included in the available variable pool. See the PHP lesson for further ways to handle the HTML form data.


Sending other data

It is not necessary to use forms to send data to server scripts. The data you send can be placed in name-value pairs separated with "&" after a "?" on the URL. Here is the URL that would have resulted from the form data in the last example. Notice the name-value pairs.

www.classAnytime.com/verify.asp?UID=234&PSWD=jakedog


Inspecting what is sent

Write this script in the html page that has the form you are inspecting. Remove the action and method attributes temporarily from the form. Then the form will be submitted to itself, where you have the script to disclose what is being sent by the form.

< type="text/javascript">
    document.write("<h1>" + location.search + "</h1>")
</script>


Example of Radio Buttons


Chocolate
Strawberry
Vanilla
When you press submit, the string
?rdoFlavor=strawberry is sent to the server. The value of strawberry is passed, and can be retrieved at the server side by ASP and PHP with the requests shown below.

In asp

  • · request.querystring("rdoFlavor") if form method is set to "get"
  • · request.form("rdoFlavor") if form method is set to "post"
  • · request("rdoFlavor") for either form method

In php

  • · $_GET["rdoFlavor"] if form method is set to "get"
  • · $_POST["rdoFlavor"] if form method is set to "post"
  • · $_REQUEST["rdoFlavor"] for either form method.


Example of Check Boxes


Monkey
Elephant
Lizard
Zebra
When you press submit, the string ?pet=monkey is sent to the server, and a single value, monkey will be sent. However, when you make multiple selections, the values will still be received as one string on the same line. For example, after you selected both Monkey and Elephant, when the variable pet is called, ASP automatically displays the values separated by a comma. See below.

In asp


Dim pets
pets = request.form("pet")
' remember, to use request.form, the form action should be set to "post"
response.write pets

So monkey, elephant is displayed. This may be a problem if you want to pass the string as separate values. The following code places the values in an array, which will separate the string into different values:


Dim iPet
For iPet=1 to request("pet").COUNT
    Response.write Request("pet")(iPet)
    Response.write " " & "<br />"
    ' displays monkey on one line, and elephant on another
Next

In php


$pets = $_POST['pet'];
echo "0) ".$pets[0];
echo "<br />";
echo "1) ".$pets[1];
echo "<br />";
...


Example of Select List



<form name="frmSelectList" method="post"
                           action="something.asp">
<select name="months[]" size="12" multiple="true">
    <option value="4" selected="selected">April</option>
    <option value="8">August</option>
    <option value="12">December</option>
    <option value="2">February</option>
<option value="1" selected="selected">January</option>
    ...
</select>

When you press submit, the string ?months=4&months=1 is sent to the server. When the variable months is called, using request.form("months") in asp or $_POST["months"] in php, the values are received as 4, 1, separated by a comma. You can change the value in the select list box to text (i.e. <option value="April".../> instead of <option value="4" ../>), if you do not want to pass the value as numbers. To receive the comma-delimited values separately, use the same method as in the previous checkbox example. This time, with form method="post". The following examples in asp and php retrieve the values and place them into arrays, with each value displaying on a new line.

In asp


Dim iMonths
For iMonths=1 to Request("months").COUNT
    Response.Write Request("months")(iMonths)
    Response.write " " & "<br />"
Next

In php


$month = $_POST['months'];
echo "0) ".$month[0];
echo "<br />";
echo "1) ".$month[1];
echo "<br />";
echo "2) ".$month[2];
  ...


Text Box Example

What's your favorite restaurant?


<form name="frmTextBox" method="post" action="TextAreaRespond.asp">
<input type="text" name="txtText" value="Joe's Bar & Grill"/>
<input type="submit" value="Submit"  />
</form>

When using form method="post", and calling the value in ASP using request.form, the value will be received as it is in the textbox: Joe's Bar & Grill. Therefore, it is not necessary to reformat the string to get rid of the "+", "%27", and the "%26" characters in place of empty spaces, apostrophe, and the ampersand, respectively. However, when you use Request.QueryString with form method="get", you will get the string with those characters. See below in Textarea Warning, an example with ASP, to address this problem. Also, when receiving the value in PHP, a backslash, "\" will be added in front of the apostrophe. For example, your output will look like this, "the boy\'s toys", instead of this "the boy's toys". To handle this problem, see below in the textarea warning section on PHP.

In asp


Dim textbox
textbox = request.form("txtText")
response.write "<h1>" & textbox & "</h1>"
'  displays "Joe's Bar & Grill"


TextArea Example

Enter your comments:


<form name="frmTextArea" method="get" action="TextArea.asp">
<textarea cols="25" rows="5" name="inputText">
    The text here will be sent as one value to the server.
</textarea>
<input type="submit" value="Submit suggestions"  />
</form>


Textarea Warning:

When using the Enter key to break lines in the textarea provided, it creates a CRLF (carriage return, line feed) within the text being transmitted to the server. This can cause problems to how the text is read. For example, if you press enter to create another new line in the textarea, HTML will put %0D%0A in place of the return to be sent to the server. On the other hand, ASP or PHP will put an empty space in place of the return when it parses the string, so at the server side, the string is being received as a single line of text.

Textarea and php

When you enter:
hello hello
hello hello

on the form and send it to a .php file, you may get hello hello hello hello, all in one line, or PHP may not even read the text after the first line break if you are storing it into a textfile. Therefore, it is necessary to replace the CRLF with the HTML line break tag <br /> before you write it into the file. The following code will replace the CRLF with the html line break tag for the transmitted textarea field: txtArea.

$crlf = chr(13).chr(10);
// storing the crlf for search/replace below

$txtArea = eregi_replace($crlf, "<br />", $txtArea);

Another problem arises when the user enters an apostrophe (') - PHP will automatically add a backslash in front of the '. The following PHP function will correct this as well.

$txtArea = stripslashes( $txtArea );

Textarea and asp

When the form is set to method="get", a QueryString displayed in the URL will be passed to the ASP page. From the ASP page, the QueryString can be called using Request.QueryString. However, this receives the whole string with + in place of a space, and %0D%0A in place of returns. Notice with the above example, the string ?inputText=The+text+here+will+be+sent+as+one+value+to+the+server is sent when the user presses "submit suggestions."


Dim suggestions, NewString, NewString2
suggestions = request.querystring     
'  calling the querystring
response.write  suggestions & "<br /><br />"  
'  displays the whole string with +'s and %0D%0A

NewString = Replace(suggestions, "%0D%0A", "<br />")

NewString2 = Replace(NewString, "+", " ")

Response.write NewString2 & "<br /><br />"  
'   the formatted string displays the string with appropriate spaces and returns.
Read about VBScript Replace Function


Checkboxes with same name

Do you want these pets?
<form name="pets" method="get" action="something.asp">
    <input type="checkbox" value="dog"  name="pet" /> Dogie?
    <input type="checkbox" value="cat"  name="pet" /> Kitty?
    <input type="checkbox" value="fish" name="pet" /> Fishie?
    <input type="checkbox"              name="pet" /> Birdie?
    <br /><input type="submit" value="Submit" />
</form>
Form
Result when all boxes checked: ?pet=dog&pet=cat&pet=fish&pet=on
Result when Kitty is checked: ?pet=cat
Result when Birdie is checked: ?pet=on

If the user presses submit with all unchecked boxes, the server pages will not receive any value from the html form page. You can validate the checkboxes and create your own error to inform the user of this error:

In asp


If not Request.QueryString("pet") Then
   Response.Write "Please select a pet value"
End If

In php


if ( !isset($_POST["pet"]) ) echo "the checkbox was not checked";


Checkboxes with different names

Do you want these pets?
<form name="pets" method="get" action="something.asp">
    <input type="checkbox" name="dog" /> Dogie?
    <input type="checkbox" name="cat" /> Kitty?
    <input type="checkbox" name="fish" /> Fishie?
    <input type="checkbox" name="bird" /> Birdie?
    <br /><input type="submit" value="Submit" />
</form>

Checkboxes with different names are essentially multiple independent check boxes. For a group of independent check boxes, make sure each name is unique, and make sure to not assign values since the names are already unique to each other. To call the values in ASP, test whether the checkbox is "on" and call each checkbox by their unique name. Therfore, the value sent to the server if a checkbox is checked is "on":


If Request.QueryString("dog") Then
   Response.Write doggie
End If
If Request.QueryString("cat") Then
   Response.Write kitty
End If

...


Form controls in arrays

Want to provide the user with several rows of the same data, all submitted together? The easiest way to handle several rows of the same controls (a column of check boxes could be used to select records, for example) is to rely on arrays to hold the user input. Your script receives arrays instead of single variables for the control values. Here is an example of textboxes, but the same code works for checkboxes and other controls, too.

Enter form data and send it to a server script

NFirstMiddleLast namee-mail address
1
2    
3  
4  
5  


Redirecting to other scripts

You have been marking up links with the <a> element to redirect visitors to to other pages or another part of a page. In client-side JavaScript you used location.href="http://..." to do the same thing. Both are examples of redirecting visitors.


Redirecting visitors with ASP

Assume for a moment that verify.asp needs to make the user ID available to all the scripts that follow. Use the response.redirect() method and concatenate the user ID as a single name-value pair. The programs that follow would use the request() method you have just learned to get the user's ID.

response.redirect("next.asp?UID=" & request("UID") )


Redirecting visitors with PHP

PHP uses a similar technique for redirecting users to another page. The catch with PHP, however, is that the header() function call must be BEFORE any output back to the browser. This requirement is usually not a problem, but if it is, you can use another redirection technique using PHP to write JavaScript (shown below). PHP syntax is explained in the PHP lesson.

header("Location: next.php" . "?UID=$UID"); exit;
or this code if you redirect after HTML output
print ("<script type=\"text/javascript\">");
print ("location.href=\"next.php?UID=$UID\"");
print ("</script>");

Advantages of server-scripting

These are the advantages you gain with server-side scripts.

  • common data files
  • fresh content (see "news stories" later)
  • visitor characteristics (see "access logs" later)
  • hiding code logic
  • shared code/source libraries
  • protection with passwords
  • protection with SSL security
  • scalable architecture (growth potential)
  • longer system lifespan
  • Web services connection

Because you have seen examples of the first two advantages of server-side scripts in this lesson earlier, only the visitor information and Web services advantages will be discussed in this section. Visitor information can be taken from the HTTP headers by your scripts. The information can be written to a database for later analysis, or used directly in scripting logic to control access to certain pages and to make allowance in markup for differences in browsers. Web services is an emerging technology that enables server scripts on differnet computers to communicate.


Visitor information

Both ASP and PHP scripts offer the means to use HTTP header information. Here are the three kinds of visitor information we will discuss.

  • How visitor linked to your page
  • Visitor IP address and host
  • Visitor browser and system


Where visitor linked from

Visitors can arrive at one of your pages by addressing your URL directly in the address bar, clicking on a Favorites link, or by clicking an anchor link on another page. The latter case is interesting because this information discloses what pages have links to your pages. If you are paying for referrals, then link information is how you figure the referral charge you owe.


IP address and host

This is the only means you have of knowing where you visitor is located. They could be on the same LAN you use, in Iceland, or at another college. IP addresses are numeric and do not tell you very much unless you happen to know which IP address blocks that ICANN assigned to particular ISP hosts. PHP has a function that looks up the host, so you can get better information.


Browser and operating system

Unlike the IP address information, browser and operating system is always accurate and useful information. Use it to understand the profile of browsers and computers used by your visitors, and the trends or changes in this profile, to make business decisions about the degree of support for certain popular and unpopular systems.

Also use this information directly in your scripting logic to control what kind of page markup the visitor should see. If you have a large number of visitors with older browsers, you may want to send them to pages without the newest browser markup features rather than watering down a common version of the page to the lowest level browser.




HTTP scripts: ASP

<%
response.write("<h1>Information about your visitors</h1>")

response.write("<h2>Where they linked from " & _
    Request.ServerVariables("HTTP_REFERRER") & "</h2>")

response.write("<h2>ISP they are using " & _
    Request.ServerVariables("REMOTE_HOST") & "</h2>")

response.write("<h2>Browser ver. and system they are using " & _
    Request.ServerVariables("HTTP_USER_AGENT") & "</h2>")
%>


HTTP scripts: PHP

<?php
print "<h1>Information about your visitors</h1>";
if(!isset($HTTP_REFERER))$HTTP_REFERER="none";  // handles case of no link
print("<h2>Where they linked from " . $HTTP_REFERER . "</h2>");
if (getenv('HTTP_X_FORWARDED_FOR')) {
    $ip   = getenv('HTTP_X_FORWARD_FOR'); // handles proxy servers
    $Host = gethostbyaddr($ip);           // looks up IP to find domain name
} else {
    $ip   = getenv('REMOTE_ADDR');
    $Host = gethostbyaddr($ip);
}
print("<h2>IP they are using " . $ip . ", and host " . $Host . "</h2>");
print("<h2>Browser ver. and system they are using " .
                  $_SERVER["HTTP_USER_AGENT"]. "</h2>");
?>


Web services

Note: Another page is devoted to information on Web Services. See 45. Web Services...this Web Services section is left here for continuity.

Because of the explosive popularity of online retail shopping and business-to-business transactions, it is clear now that we need for our pages to contain cost data such as invoice details, shopping cart details and so on.

A business today uses suppliers, subcontractors, and other business alliances necessary to offer complete products and solutions to customers. For example, L.L. Bean sells shoes on the Web, but UPS is the shipper.

The L.L. Bean Web server needs to be able to ask the UPS server, for example, what the charges are for shipping your oxfords from Freeport, Maine to Oxnard, California in two days. The charge could then be added to your online shopping cart page.

Web Services, a new technology, is a way of transferring data over the Internet using standard HTTP, XML, and TCP/IP that we have studied in this course. A Web Service is not a page and not intended for our eyes, it is a remote request for information or data that a server script can issue.

Amazon extends its reach with Web services

by Scarlet Pruitt, 8/9/2002 (source: IDG.net)

Amazon.com rolled out the welcome mat Tuesday for Web site developers and owners to build applications and tools that will allow them to incorporate Amazon's offerings into their sites.

In a bid to drum up more traffic and sales, the e-commerce giant is offering Amazon.com Web Services for free, allowing third-party sites to search and display Amazon products.

The Web services can be accessed at http://www.amazon.com/webservices through both XML (Extensible Markup Language) and SOAP standards (Simple Object Access Protocol). The services will also be integrated into Amazon's Associate Program, which allows sites to earn referral fees from purchases made at Amazon via links on their sites.

For more information look into Builder.com which has a series of informative articles and examples of Web Services.


XML carries services

SOAP (Simple Object Activation Protocol) is the XML grammer used for Web Services message formats. A client application (your server script) requests services on a remote server via a SOAP message. An example of a horoscope request wrapped up in the SOAP envelope is shown below. If you want to include accurate and timely horoscopes on your Web pages, you would write a SOAP file with the person's sign included <sign></sign> and send the XML file to a known Web Service.

SOAP file

Another of your server scripts receives the horoscope inside a SOAP XML file (see that envelope below) which is the servers response to your request above. Your server script has to parse the <horoscope></horoscope> container to extract a timely horoscope that can be included on your xhtml page.

SOAP file


Locating Web Services

Looking for interesting Web Services? The Universal Description, Discovery and Integration (UDDI) protocol is a common format for listing services you could use. Check the UDDI Site maintained by Microsoft, the Oasis site for UDDI.org, look for 'horoscope' at SOAPClient's UDDI search, or use Google ("Web Service" horoscope).

IBM provides an excellent site for finding services. A sample screen shot after querying for "Stock Quote" is shown below. IBMs UDDI Web Service Browser

IBM Browser

Mastery test