| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
41. Server introductionIntroduction (click any heading below to return here)Up to this point in the course you have designed and authored client-side Web pages using HTML, 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.
|
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? |
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. Check for popular shareware log analyzers.
The ASP technology interprets your instructions for generating dynamic HTML 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 HTML markup.
Your ASP pages will consist of HTML 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 HTML 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 HTML sent to the browser. The markup received at the browser looks like common HTML, but it is dynamically written.
Both client and server scripts need to write HTML. You learned to write client scripts that write HTML when you studied JavaScript. Here are VBScript examples that introduce an important DOM syntax difference between clients and servers.
Client scripts use the document
object to write HTML.
<script language="VBScript" type="text/vbscript">
document.write("<p>Written by a client script</p>")
</script>
Server scripts use the response
object to write HTML.
<%
response.write("<p>Written by a server script</p>")
%>
There is an introduction to ASP and example scripts in a later lesson.
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?
Once the server recognizes the ASP extension, it then goes through the process of dynamically creating the HTML 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 HTML. This code (located within the ASP delimiters) will be found in the form of scripting languages.
<%@ Language=VBScript %>
<!DOCTYPE html>
<html>
<head>
<html lang="en-US">
<meta charset="UTF-8" />
<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 HTML.
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.
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>
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.
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>
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.
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 HTML 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 HTML 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 HTML sent to the browser. The markup received at the browser looks like common HTML, but it is dynamically written.
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.
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).
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 HTML page.
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.
Request line
contains the following information:
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 HTML 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 HTML forms.URL
of the requested fileversion number
of HTTPThe 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:
General:
information about the client or the serverEntity:
information about the data being sent between the client and the serverRequest:
information about client settings and different types of acceptable information.If POST
was used with the HTML form request, then this segment contains the form data sent to the server. Otherwise, nothing is sent in this part.
The response line returns two things:
The response header has these categories:
General
: information about the client or the serverEntity
: information about the data being sent between the client and the serverResponse
: information about the server and specifics about the responseWith a successful request, the HTML 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.
Here are a few examples that show the major elements in HTTP packets.
HTTP Request | HTTP Response |
---|---|
Request Line | Response Line |
|
|
Header | Header |
|
|
Body | Body |
(Contains data only when POST method used in HTTP request) |
<HTML> (....HTML markup) </HTML> |
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.
A major advantage of server-side scripting is the ability to have reusable source code that can be appended to your HTML 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.
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 HTML, the server logic will look for lines like the one below. When found, the files will be included in line with your HTML 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.
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 HTML 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.
You also may include files in your PHP scripts. Here, the assumption is that you will include HTML 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 HTML markup. The file footer.php, on the other hand, must begin and end with the PHP container tags <?php ?>
.
Imagine you have an HTML form that submits a user ID and password to an ASP/PHP program for verification. The HTML 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>
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")
.
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.
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
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.
<script>
document.write("<h1>" + location.search + "</h1>")
</script>
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. |
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. |
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
$pets = $_POST['pet'];
echo "0) ".$pets[0];
echo "<br />";
echo "1) ".$pets[1];
echo "<br />";
...
|
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.
Dim iMonths
For iMonths=1 to Request("months").COUNT
Response.Write Request("months")(iMonths)
Response.write " " & "<br />"
Next
$month = $_POST['months'];
echo "0) ".$month[0];
echo "<br />";
echo "1) ".$month[1];
echo "<br />";
echo "2) ".$month[2];
...
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.
Dim textbox
textbox = request.form("txtText")
response.write "<h1>" & textbox & "</h1>"
' displays "Joe's Bar & Grill"
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>
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.
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 );
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
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>
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:
If not Request.QueryString("pet") Then
Response.Write "Please select a pet value"
End If
if ( !isset($_POST["pet"]) ) echo "the checkbox was not checked";
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
...
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.
N | First | Middle | Last name | e-mail address |
---|---|---|---|---|
1 | ||||
2 | ||||
3 | ||||
4 | ||||
5 | ||||
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.
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") )
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>");
These are the advantages you gain with server-side scripts.
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.
Both ASP and PHP scripts offer the means to use HTTP header information. Here are the three kinds of visitor information we will discuss.
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.
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.
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.
<%
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>")
%>
<?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>");
?>
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.
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.
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 HTML page.
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