| CIS 209 | Web Page Scripting Languages |
In the last chapter, we learned that there are several objects within the ASP model, each with its own properties and methods that we can access from scripts. In PHP, we accessed the variables from scripts, with the same result. In this chapter, we will learn how to use two of these objects, the request object and the response object, to process a form, retrieve server variables (PHP calls them environment variables), write content to the browser, and redirect the user to another page.
When the browser makes a request of the Web server, it sends along with the request a list of extra variables. PHP calls them environment variables. ASP calls them server variables. (HTTP Info.htm)
When the browser sends a request to the server, the request will include:
The Request object, in ASP, allows us to retrieve this information. Cookies are retrieved using the cookies collection in ASP. PHP uses the cookies function. Client certificate fields are retrieved using the ClientCertificate collection. The form and QueryString collections allow us to retrieve information sent from a form. Information that is sent with the request in the HTTP header can be retrieved using the server variables collection.
The Response object is used to send information to the browser. Server information like the IP address of the server, operating system of the server, web server software version is sent. The cookies collection can send a cookie to the browser. A status code is sent to indicate that the request was successful or encountered an error. The response object allows us to redirect the browser to another page. The response object allows us to append information to the Web server log, and add custom information to the HTTP header.
A form passes name and value pairs to the Web server. The name and value are separated by an equal sign (=). Each name/value pair is separated from the next by an ampersand (&). The two methods that pass the form field information are the GET method and the POST method.
The GET method appends the name/value pairs to the URL with a question mark (?). The POST method sends the name/value pairs as part of the HTTP request body. We tell the browser which method to use by specifying the METHOD property of the <FORM> tag.
The request object contains a forms collection and a QueryString collection. If the form is sent using the GET method, the QueryString collection is used to retrieve the name/value pairs. In PHP, we use $_GET["var"]. If the form is sent using the POST method, the forms collection is used to retrieve the name value pairs. In PHP, we use $_POST["var"].
Just remember we POST FORMS and GET QUERYSTRINGS. In PHP, we use $_POST and $_GET so it is easier to remember.
The name value pairs are sent URL-encoded, which means that spaces are replaced with plus signs (+), and special characters are replaced with the percent sign (%) and the hexadecimal value for the character. To retrieve the name/value pairs exactly as they were sent, we would have to split the name value pairs, parse the name and values, then replace the plus signs and hexadecimal values with blank spaces and the special characters. The request object does all this for us, just as PHP uses $_GET and $_POST.
Check out the EXAMPLE from the last chapter which demonstrates the differences in the GET vs. the POST methods, and demonstrates exactly how the name/value pairs are sent URL-encoded using the GET method.
The syntax for retrieving the entire form collection is:
request.form
The following example illustrates how we can detect if a user has completed a form with a script on the server. However, it is much better to test this locally (on the client) with JavaScript code - saves network traffic! Check out the ASP EXAMPLE. Here's a similar PHP EXAMPLE. If the form field does not have a form field name specified in the form field tag, the value will not be sent.
To retrieve a single field from the form collection, specify the request object name, the form object, and the name of the field, inside quotation marks. Below is the syntax for retrieving a single field from the form collection.
Request.form(“formFieldName”)
The following EXAMPLE - 282ln08post.asp demonstrates how to retrieve the values from a form using
the form collection. The
<% response.buffer="true" %> statement will hold the
results from the server scripts at the Web server until all scripts are
executed. Take a look at this EXAMPLE -
282ln08post.php for a demonstration of how to retrieve the values of a form
with PHP.
The QueryString collection allows you to retrieve the name and values of
fields from a submitted form. The QueryString collection can retrieve the entire
QueryString collection or an individual field. To retrieve the entire
QueryString collection, specify the request object name and QueryString. The
following sample code shows how to retrieve the QueryString using the request
object and the server variables collection.
<% = request.querystring %>
<% = request.servervariables (“QUERY_STRING”) %>
To retrieve a single field from the QueryString collection, specify the request
object name, the QueryString object, and the name of the field, inside quotation
marks.
request.querystring(“fromFieldName”)
In our previous ASP example (282ln08post.asp) you can change all the references to
request.form to request.querystring and you will get the
same results. Here it is - 282ln08get.asp.
In our previous PHP example (282ln08post.php) you can change all the references to
$_POST to $_GET and you will get the
same results. Here it is - 282ln08get.php.
Since the QueryString and form collections are child objects of the request object, we can list the names and values of fields without knowing the names of the fields. We will use the For Each statement.
To create a Web page that displays the names and values of fields without knowing the names of the fields, we can use a For Each statement. The following code demonstrates the syntax to display the names and values without knowing the names.
<% dim formField
for each formField in request.querystring
response.write formField
response.write " = "
response.write request.querystring (formField)
response.write "<br>"
next %>
Check out the 282ln08getall.asp example.
In PHP, you can use the following code to display the names and values of fields without knowing the names of the fields.
<?
reset ($_POST);
while(list($key, $val) = each ($_POST))
print $key . " = " . $val . "<br>";
?>
Here is a link to a page we did just a moment ago, that did just this - 282ln08CheckEmptyForm.php.
Besides text boxes, forms can contain drop-down lists, radio buttons, and check boxes. Both request objects, the Form collection and the QueryString collection can be used to retrieve the values from these form elements using ASP. Which collection we use, depends upon the method used to send the form. We POST forms and GET QueryStrings. In PHP, we use $_POST or $_GET.
Drop-down List Boxes:
The <SELECT> tag identifies a drop-down list box in a form. The drop-down list box can display one option at a time, or the entire list, by using the size property.
There is no difference between the code used to display a text box and the code used to display the selection from a drop-down list box. The only difference is that the user can select more than one item from a drop-down list box if the MULTIPLE property is specified. The user will hold down the SHIFT key or the CTRL key to select multiple items from the list.
When the script receives the values from the form field, all of the values from the form field will appear in a comma-delimited list. The only way to retrieve the individual values from a multiple selection list is by referring to the options by their index number and the name of the form field. The index number for a drop-down list box in ASP begins with one, not zero as with other arrays.
The following ASP EXAMPLE shows the syntax
of setting up a selection drop-down box in HTML and then displaying the choices
selected using a server-side script. This PHP
EXAMPLE shows the PHP syntax, a little different since PHP uses the "Array
From Form Element" feature - just name the select element the name plus [
] to indicate that it is an form element array.
Check Boxes and Radio Buttons:
Check boxes and Radio Buttons use the <INPUT> tag with the TYPE property set to checkbox or radio. Radio buttons only allow the user to select one choice. The VALUE property can be specified for each check box or radio button. If the VALUE property is not specified, the value that is sent when the form is submitted is ON. No value is sent if no option is selected when the form is submitted. We can use the CHECKED property to insure that one option is selected. The user can select multiple check boxes.
The syntax in ASP to retrieve the check box value using the Form and QueryString collections is:
<%
request.form("FormFieldName")
request.querystring("FormFieldName")
%>
If you assign the same name to multiple check boxes, the entire form collection will display the name and value for each check box selected. If you specify the field name, the values of the check boxes will appear in a comma-separated list in ASP. You can specify the index number to display the check box results.
You can specify the number of values in a form field by using the keyword COUNT with the following syntax:
request.form("FormFieldName").count
OR
request.querystring("FormFieldName").count
Check out the 282ln08chkrad.asp example which demonstrates how we can display the number of check box values the user has selected, their values, and a radio button selection using ASP.
PHP is similar, but we'll use $_POST['FormFieldName'] to retrieve the check box values or $_GET['FormFieldName'] if get method is used. In order to loop through the array of checkbox values, we use:
foreach
($_POST["chk1"] as $chk1) But, we will first check to make sure values have been selected with:
{
echo $chk1 .
"<br>";
}
if (count($NameOfCheckboxArray) !=0) {
// code here
}
So, our code to display the checkbox values that are checked will be:
if (count($NameOfCheckboxArray) !=0) {
foreach ($_POST["NameOfCheckboxArray"]
as $chk1)
{
echo $chk1 .
"<br>";
}
With PHP, we must name the checkbox form elements in our HTML with the
appended brackets ( [ ] ) to indicate we have an array.
In PHP, You can specify the number of values in a form field by using the keyword COUNT with the following syntax:
count($NameOfCheckboxArray)
Check out the 282ln08chkrad.php example which demonstrates how we can display the number of check box values the user has selected, their values, and a radio button selection using PHP.
The server variables are a collection within the request object. When a browser sends a request for a page to a Web server, it also sends information in the HTTP headers. This information, which includes the name of the page requested, the IP address of the destination Web server, and the IP address of the client, is used to process the request. Therefore you can use the request object to retrieve the names of the HTTP header fields and their values.
request.servervariables("SERVER_VARIABLE_NAME")
The code below demonstrates how to display the server name on a Web page, each section of code achieves the same result.
<% = Request.ServerVariables("SERVER_NAME") %>
<% response.write Request.ServerVariables("SERVER_NAME") %>
<% dim strServerName
strServerName = Request.ServerVariables("SERVER_NAME")
response.write strServerName
%>
The following table shows more of the server variables that can be used by your scripts.
|
Variable Name |
Description |
Example |
|
SERVER_NAME |
The name of the Web server |
www.domainname.com |
|
SERVER_SOFTWARE |
The operating system of the server and the Web server software |
Microsoft-115/4.0 |
|
SERVER_PORT |
The number of the requested server port, the default is 80. |
80 |
|
LOCAL_ADDR |
The local IP address of the server’s computer |
153.90.192.1 |
|
SERVER_PROTOCOL |
The protocol being used to deliver the request (HTTP 1.0 or HTTP 1.1) |
HTTP/1.1 |
|
HTTP_REFERER |
The current page the client is requesting the new page from |
http://www.domainname.com/index.asp |
|
HTTP_USER_AGENT |
The name of the user agent that can be used to determine the browser name and version used on the client |
Mozilla/4.0(compatible; MSIE5.0;Windows 98; DigExt) |
|
REMOTE_ADDR |
The remote IP address of the client’s computer |
207.252.246.222 |
|
URL |
The URL of the file being requested |
/ip/FormCheckbox.asp |
|
PATH_INFO |
The virtual path to the file being requested |
/ip/FormCheckbox.asp |
|
PATH_TRANSLATED |
The virtual path translated into the physical path |
C:\inetPub\wwwroot\ip\FormCheckbox.asp |
|
REQUEST_METHOD |
The method that a form is using to send information – either post or get |
POST |
|
HTTP_CONTENT_LENGTH |
The length of the file attached to the header, which may include the results from a form that uses the post method, if the get method is being used the value is 0 |
61 |
|
QUERY_STRING |
The querystring generated from the name and value pairs from a form that used the get method |
chk2=mark&chk3=op&rad1=fin&brnSubmit=Submit |
|
HTTP_COOKIE |
Name and value of a cookie if the client has one written from the same server |
CookieColor=Green |
Here is an ASP EXAMPLE of how we might obtain visitor information from our visitors. This ASP EXAMPLE demonstrates how we can loop through the server variable collection and display each name and value.
Instead of using the HTTP_USER_AGENT to detect the browser version, it is more useful to detect what features the browser supports using the Browser Component object, which we'll look at in Chapter 10.
PHP uses environment variables instead of the server variable collection. When a browser makes a request of a Web server, it sends along with the request a list of extra variables which can be accessed in PHP by displaying environment variables.
See http://www.php.net/manual/en/language.variables.predefined.php for more PHP environment variables.
Here is a PHP EXAMPLE of how we might obtain visitor information from our visitors. This PHP EXAMPLE demonstrates how we can loop through the environment variables and display each name and value.
Unlike standard HTML redirection, when you use server-side redirection, the client cannot stop the redirection from occurring, and the user is not even aware that they have been redirected.. The redirect method sends an HTTP header to the browser that says “HTTP/1.1 302 Object Moved” and “Location/newpath/newwebpage.asp”
In ASP, to redirect the user, simply call the redirect method of the response object. The redirect method takes one parameter, the destination URL. The following sample code shows how to redirect a user with server-side redirection using ASP.
<% response.redirect(http://www.course.com) %>
Or you can redirect using a variable.
<% dim strGo
strGo = http://www.course.com)
response.redirect(strGo)
%>
You can combine the redirect method with other methods. You can use IF statements, Select Case statements, or any other conditional loop to choose different Web pages to redirect the user.
The following ASP EXAMPLE will allow the user to select one of three web sites from a drop down list, then they will be redirected to the address chosen.
In PHP, we redirect the user to a new page (http://www.course.com as an example) with the code:
header( "Location: $_POST[http://www.course.com]");
Be careful!!! In PHP, you'll get an error if there is ANYTHING (any HTML, or even just a space) before the above code. It MUST be sent to the browser before anything else!
This PHP EXAMPLE demonstrates how to allow the user to select on of three web sites from a drop down list, then be redirected to the address chosen. Note that this example simply passes the URL as a value to the next page. We could have done the above ASP example the same way.
In this section, you will learn to control how the output is sent to the browser. Information that is sent to the browser is sent in the HTML output stream, which is called the buffer. When the buffer property is set to true, you can write ASP and HTML statements that are held in the buffer until you direct the buffer to release the output stream to the browser. The response object has a method called flush that releases the output stream to the browser, and another method called clear that erases the contents of the buffer without releasing it to the browser.
The following ASP EXAMPLE demonstrates how to use the buffer and response methods
and to detect whether the user selected a correct answer. However, I remarked
out response.buffer="true" and all the response.flush
commands and did not see a difference. It seem to work the same and at the same
speed. This is most likely because IIS5 has the response.buffer set
to true by default.
In PHP, we use the flush() function to push all the output from the buffer to the browser. To hold output to the browser in PHP, we can call the ob_start() function to open a new buffer and wait for the ob_end_flush() function to send the data to the browser and close the buffer. You can use the ob_start() function with ob_end_flush() to detect whether the user selected a correct answer. Check out this link - http://www.php.net/manual/en/function.ob-start.php from the PHP manual.
However, whether to flush or not depends on the traffic to the site. Check out http://www.learnasp.com/learn/whybuffer.asp.
When you cache a Web page, you instruct the browser to store a local copy of the Web page and all of its contents in a temporary directory on the client.
• response.cachecontrol = “Public” – setting the property to Public prevents
caching.
• response.cachecontrol = “Private” - (default) allows the
proxy server to cache the Web page.
The expires property of the response object is used to specify the number of minutes after which the cached versions of a Web page should expire. Once the cached Web page expires, the browser must retrieve the Web page from the Web site. Below is a sample of how to set the cache to expire in 5 minutes and on a specific date and time.
<% response.expires = 5 %>
<% response.expiresabsolute = #Dec 31, 2001 12:00:00# %>