News Outline Schedule Tutorials Project Tools Links

1: What is it?

While the JavaScript that we have been learning so far in this course is all run on the web browser, or the Client Side of the connection meaning that the viewer's computer is doing all of the work, Server Side scripting takes place on the web server itself. This means that the script will potentially have access to a much larger amount of data than it would if it was running on the viewer's machine. Scripts run on the server will be able to gather data from all visitors to a web site, counting the number of times anyone looks at your page, providing message boards, dynamically generating content and the like.

Server side scripting existed a long time before JavaScript. Originally, the only way a web page could be interactive at all was by having the user submit HTML forms to a server side script, and processing the results there. The addition of JavaScript has improved the interactivity of web pages considerably, and the combination of Client Side scripting and Server Side scripting can be very powerful.

Server side scripting has evolved considerably since the early days of the world wide web, but it is very important to remember that it will always have a few limitations. Server Side scripts can not interact with the user on nearly as intimate a level as client side scripting such as JavaScript, because of the way server side scripts work. When the user loads a page from a Server Side Script, any and all information the script is going to receive is sent in the HTTP request. The script can access any information on the server, but as far as input from the user, that request is the only thing possible - because of this, you can not stop in the middle of a server side script and ask the user for more information! The only information the script can send back is the resulting web page (or other file) to be sent as the response to the request.

2: CGI Programs

In some cases the whole web page is created by a program on the web server - this is usually called CGI (Common Gateway Interface). In these cases, the CGI program is responsible not only for generating the content for the web page, image, or other file to be downloaded, it is also responsible for setting up and sending the HTTP Header to tell the web browser what to do with the data.

A CGI script can be written in any language which can run on the web server in question. Many CGI scripts are written in perl, which is a powerful (and free) scripting language that is available on all UNIX Systems, and which can also be installed on windows platforms. On Windows platforms, Visual Basic may be used as well, and on any platform, programs can be written in C or any other compiled language, and then used to generate the web pages. In the case of CGI programming, the limit of which language is available rests on the operating system that the Web Server is installed on, and not with the web server itself.

When a web page has been generated by a CGI script, it will usually have /cgi-bin/ in it's path, or the file will have an extension other than .html, such as .cgi, or .pl. This information is used by the Web Server to determine that the file should be executed as a program, instead of simply delivering it's contents to the viewer. In the case where the URL's path contains /cgi-bin/, a special directory is set aside for scripts, and anything in that directory will be treated as a script by the web server. In cases where this path name is not present, the Web Server can be set up to recognize any file with a certain extension (such as .cgi, or .pl) as a CGI script, and run it. In most cases, the specifics depend on the Web Server being used, and how it is configured.

One of the major advantages of CGI scripts is that the file sent to the viewer does not need to be an HTML file. The script can instead be set up to deliver a plain text file, Images, (as is done with most web counter programs,) or any other type of file. This is because the CGI script is responsible for the HTTP Header, which determines what type of file is being sent to the browser. Other types of server scripts, such as server side includes, and the like are not responsible for the header, and as such can only be used to send back HTML files.

The biggest disadvantage of CGI is that it is often much more complex to do a simple task than it needs to be. Below is an example of a CGI script written in perl which displays the current date (according to the web server) - in practice, this would have also printed out a much larger HTML file, the date itself being only a minor part of it:

#!/usr/bin/perl @days = ('Sunday','Monday','Tuesday','Wednesday','Thursday', 'Friday','Saturday'); @months = ('January','February','March','April','May','June','July', 'August','September','October','November','December'); ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time); if ($hour < 10) { $hour = "0$hour"; } if ($min < 10) { $min = "0$min"; } if ($sec < 10) { $sec = "0$sec"; } $year += 1900; $date = "$days[$wday], $months[$mon] $mday, $year at $hour\:$min\:$sec"; print "Content-type: text/html\n\n"; print "<html>\n"; print " <head>\n"; print " <title>The current time is</title>\n"; print " </head>\n"; print " <body>\n"; print " <h1>\n"; print " It is now <b>$date</b>.\n"; print " </h1>\n"; print " </body>\n"; print "</html>\n";

As you can see, CGI scripts can involve an enormous amount of effort to achieve a small amount of effect. For this reason, many newer forms of server side scripting have been developed since then.

3: Server Side Includes

As a solution to the problem of CGI needing so much effort for small effects, the makers of the NCSA HTTPd, (one of the very early Web Servers, upon which the popular Apache Server is loosely based,) came up with Server Side Includes. A special file name extension was created (.shtml) which, when used on a file, would inform the web server that this file contained some special HTML tags which were to be interpreted and replaced by their output before sending the page to the Browser. The format they chose was to place the new tag inside of an HTML comment, just to avoid conflict with moving pages to web servers that did not support the tag. A typical Server Side Include tag would look something like this:

<--#command exec="runthis.sh" -->

Where runthis.sh would either be a simple shell command, or the name of a program on the server which could be executed, and it's output used in place of the tag. If runthis.sh's output was for a counter on a web page, the web server might have replaced it with something like this:

This page has been visited <img src="/cgi-bin/number?n=231" alt="231"> times.

In the case above, /cgi-bin/number would be a script located on the Web Server which produced an image of the number it was provided. For more information on how Server Side Includes worked, you can find a tutorial on them here, for one of the many variants of this technique, published in 1995.

The example from the CGI section of displaying the date could now be done easily, just by embedding a single tag in a regular HTML file, and getting the date from a separate program (which we would also have to write):

<html> <head> <title>The current time is</title> </head> <body> <h1> <--#command exec="getDate.sh" --> </h1> </body> </html>

This was a considerable time saver, but still not perfect. The HTML file itself was much cleaner, but we still have to write the program which gets and displays the date, and Server Side Includes were often very difficult to set up, and the method for doing so, the special tag involved in them, and the languages available to write the program itself in all varied from one system to another.

One other disadvantage to Server Side Includes was that since the code was embedded in a regular HTML file, you could only use them to produce HTML code - scripts which produced images, .pdf files, or other things were not possible with Server Side Includes.

4: ASP Scripting

Active Server Pages, or ASP for short, was Microsoft's answer to the difficulties with Server Side Includes for their web server, IIS. Rather than use the already established format of Server Side Includes, Microsoft decided to come up with their own way of doing things from scratch. Rather than relying on the administrator of the site installing scripting languages and the like for the people making web pages, they decided to use the Windows Scripting Host as the mechanism through which the embedded program code is executed. This means that any language which has been installed on the machine and registered with the Windows Scripting Host can be used in an ASP web page, but if you do not specify the language at the outset, then it will default to VBScript, which is assumed to be installed on all systems running Windows.

Like Server Side Includes, ASP pages contain mostly regular HTML code, with a few special tags included in them that are interpreted by the Web Server, and replaced with whatever output they produce in the final page which is then sent to the Web Browser. A typical ASP tag would look like this:

<% Program Code Here %>

Where Program Code Here would be a short program written in VBScript. Since this code is in a full featured programming language, instead of being limited to absolutely basic shell commands, ASP pages can be easier to write, since complex functions can be created inside of the tag, instead of requiring that you write a separate script file to perform the task.

Our example for before in ASP would look like this:

<html> <head> <title>The current time is</title> </head> <body> <h1> <% theTime = now() response.write "It is now <b>" & theTime & "</b>." %> </h1> </body> </html>

5: PHP Scripting

PHP was developed by the UNIX community to provide a superior alternative to Server Side Includes, in the style of ASP, but without the dependance on Microsoft's IIS Web Server. The name PHP is a recursive acronym for PHP: Hypertext Preprocessor. Unlike ASP however, PHP will run on nearly any web server or platform, though the most common to see it running on is the Apache Web Server. PHP is typically included into a page like this:

<?php PHP Code Here ?>

Where PHP Code Here would be a program written in PHP. The syntax of PHP is very similar to C syntax, and it is designed to provide as much flexibility for making web pages as possible, without making the language too difficult to learn. More information about PHP can be found here.

Our on-going example of displaying the date in an HTML file for PHP actually looks very similar to the one for ASP:

<html> <head> <title>The current time is</title> </head> <body> <h1> <?php $theTime = date("r"); print "It is now <b> $theTime </b>."; ?> </h1> </body> </html>

6: Other types of Server Side Scripting

The examples given above are not the only methods of Server Side scripting. Many different methods have been invented, and are still being created even now, including Java Server Pages (which are usually the focus of the course 60-334, the Lotus Notes system used by the University of Windsor's web sites, and other special purpose server scripting systems such as the ones embedded in database servers.

7: Practical Examples

To demonstrate some of the topics we've discussed previously about web servers, and server side scripting, below are some practical examples of server side scripts, done using the PHP server side scripting language.

7.1 Beginning PHP

PHP scripts are normally embedded into regular HTML files with a special tag <?php ... ?> tag. When the web browser requests a PHP page, the server takes the file, and scans through it for <?php ... ?> tags, interprets them, and replaces them in the file with their own output. Only after all of this is done is the resulting web page passed back to the browser. The result of this is that the browser never actually sees any of the PHP code - it is all dealt with on the server side.

Here we have an example PHP program, along with the HTML output that the browser would actually receive from it:

PHP Code:Browser sees:
<html> <head> <title>First PHP program</title> </head> <body> <h1><?php print ("The Output!"); ?></h1> </body> </html> <html> <head> <title>First PHP program</title> </head> <body> <h1>The Output!</h1> </body> </html>

As you can see, the PHP code is completely removed from the resulting web page, and only the output from the print command actually appears in it's place, and the browser never sees the program code - the server runs the program code for us to generate the web page. In this case, we only have one command to run (a print command), and the output from that code is all that the browser receives.

7.2 Comments in PHP

As with any programming language, once your program reaches a certain size, you will need to include comments to explain what you were doing, so that when you come back later to work on it again, you will be able to understand what you were doing in the program. This is even more important to do when you are working on a project with a number of other people, where proper comments can save your co-workers literally hours of head-scratching in their attempts to figure out what the program is doing. As an example of the kind of difference the presence or lack of comments can make in a program, here is an example of a program which produces a web-based counter with no comments, and here is the same program with comments added in. Both programs work exactly the same, but one is roughly twice the size of the other due to the comments added in. The extra space used does not make the program slower in any way, since the server ignores the comments, but when someone comes back to look at the program later, they will definitely prefer to work on the one with comments. (Side note: You do not need to understand this program for this course - they are just there as an example of the usefulness of comments!)

There are three types of comment accepted in PHP, two are the same as the comments used in JavaScript (// ... and /* ... */) plus an additional type of single line comment used commonly in other server-side scripting languages, where the comment line begins with a #. Here is a version of the example program shown above with all of the types of comments added in:

PHP Code:Browser sees:
<html> <head> <title>First PHP program</title> </head> <body> <h1><?php // JavaScript type one line comment print ("The Output!"); /* JavaScript type multi-line comment */ # another one line comment ?></h1> </body> </html> <html> <head> <title>First PHP program</title> </head> <body> <h1>The Output!</h1> </body> </html>

As you can see, the comments have absolutely no effect on the resulting web page - they exist only to provide information to people working on the program about how it works, and what it is doing. With any of these comments, the server will completely ignore anything that is inside of the comment - thus everything on the line after a // will be ignore by the server. It is important to make sure you do not accidentally comment out your closing ?> tag, as this will cause the server to ignore it as well, and think that the rest of your HTML code is actually supposed to be PHP program instructions.

Bad:Good:
// end of script ?> // end of script ?>

7.3 Storing Information

When using a variable in PHP, all that is needed is to pick a name for your variable and start using it - it is not necessary to declare your variables before using them. The names of variables in PHP have the same limits on them as variable names in JavaScript - you must start the name with a letter, and you can only have letters, numbers and possibly the _ character as part of the name of your variable. The names of your variables are case sensitive, so if you start with a variable called thisIsMyName, you need to keep the capitalization exactly the same all through your program. Another important thing to remember about variables in PHP is that before every variable name, you must place a $ - this special character tells the PHP server that the name it's about to receive is a variable, and should be treated as such. In fact, this $ character will make something be treated as a variable even inside of a print statement, like in the following example:

PHP Code:Browser sees:
<html> <head> <title>First PHP program</title> </head> <body> <h1><?php $myVar = "Output"; print ("The $myVar!"); ?></h1> </body> </html> <html> <head> <title>First PHP program</title> </head> <body> <h1>The Output!</h1> </body> </html>

In the above code, we're setting the variable $myVar, and then we print out a line of text - the variable $myVar is inside of that text, but because of the $ at the start of it's name, the PHP server treats it as a variable and replaces it with it's value in the output.

It should be noted that PHP will try very hard to avoid causing program errors when it can - because you don't need to declare your variables ahead of time, if you try to take data from a variable which does not exist, it will not cause an error. Instead, PHP will simply create the variable you have attempted to read from, and set it to be empty. Printing empty variables results in an empty string (""), and when you attempt to do math with them, they are treated as though they contain the number zero. Because of this, you need to be very careful that you are typing your variable names correctly - if your program is claiming there's nothing in the variable, and you are sure there should be something there, make sure you haven't accidentally miss-spelled the name somewhere.

This substitution of variable names for their values is a very useful tool for producing your output - you don't need to worry about how to concatenate strings together, or anything else, just put the name of the variable in, and out it comes! There is a problem however - since everything starting with a $ is considered to be a variable name, how do we print out a $? To do this, we must place a \ character in front of it, to escape the $ character. There are a few other characters that you can not include in a printed out string without escaping them, such as the double quotation mark (") or the new line character. Here is a short list of some of the characters that need to be escaped:

To print thisType this:
$\$
"\"
<new line>\n
\\\

7.4 Arrays in PHP

As with any other variable in PHP, to begin using an array, we merely need to type it's name and start using it - with arrays, we merely need to add in an index for which element in the array we want to set in square brackets after the array's name, such as $myAry[16]. If we want to fill up an array in PHP, but don't want to bother setting the indexes, we can just leave it out, and PHP will guess the next available index for us, like this:

The PHP CodeThe array holds:
$fluffy[] = "first"; $fluffy[] = "second"; $fluffy[27] = "third"; $fluffy[] = "fourth"; $fluffy[] = "fifth"
IndexContents
0first
1second
27third
28fourth
29fifth

As shown above, if your array is new, [] will start with an index of 0, and will progress from there, but if you set another value (such as 27) then it will continue after that. The empty index ([]) will always be one higher than whatever the highest numbered index you've used is.

To find out how many elements have been stored in an array, we can use a special function called count - it will tell us exactly how many filled elements there are in our array - but it won't tell us what the highest index is. Thus for the array shown above, count($fluffy) would return 5 - not 29 or 30, because only 5 elements of the array are actually being used. Obviously, this can create a problem if we wanted to use a for loop to scan through our array, it wouldn't work, since there would be nothing at indexes 2, 3, and 4. to make up for this, PHP has introduced a new type of loop, designed specifically for dealing with arrays, called a foreach loop. Here is an example of how foreach can be used to scan through the array we used above, and print out the table in the second part of that example:

<?php $fluffy[] = "first"; $fluffy[] = "second"; $fluffy[27] = "third"; $fluffy[] = "fourth"; $fluffy[] = "fifth" ?> <table> <tr><th>Index</th><Contents</th></tr> <?php foreach ($fluffy as $flufIndex => $flufValue ) { print("<tr><td> $flufIndex</td><td>$flufValue</td></tr>\n"); }; ?> </table>

The above code will produce the table from the previous example which lists the contents of the $fluffy array. The foreach loop starts by giving the name of the array being accessed (in this case, $fluffy) and then two new variable names. (Here, $flufIndex and $flufValue.) These two new names will be used in each trip through the loop to hold the index and value of the array at that index. Thus, on the first trip through the loop, the index is 0, and the value at $fluffy[0] is "first", so $flufIndex will hold 0, and $flufValue will hold the string "first". On the next trip through the loop, $flufIndex will be updated to the next index in the $fluffy array, and $flufValue will be updated to whatever is in $fluffy[$flufIndex].

PHP even allows us to give strings as indexes for our arrays, like $myAry["where"]. (Technically, this means that they are actually something programmers refer to as a hash, but since they're otherwise treated the same, and the PHP documentation itself calls them arrays, we're going to do the same.) Being able to give a string as the index does sometimes make it difficult to access the contents of the array from a loop, but the foreach loop above works equally well with string indexes or numbers.

8: Getting input from Forms

8.1 Dealing with Forms in PHP

One of the biggest reasons for using server side scripting is to be able to deal with forms submitted by the viewer - whether we're mailing that information somewhere, storing it in a log file, or just giving back other information based on what was entered to the form. To deal with this form, we need to be able to get the information from the form and bring it into our program. To do this, there are two special arrays built into PHP which contain all of the form items which may have been submitted.

The first array is called $_GET, and it contains all of the items submitted to the script IF the form used the GET method. (ie: <form method="GET" action="a.php">) In this situation, the $_GET array will contain each of the form items submitted, with the name as it's indexes, and the value of each item as the contents of the array at each index. If your form had an input tag of type text, with the name data, then $_GET["data"] would contain whatever had been typed into the text input box it produced.

The second array is called $_POST, and it would contain all of the values submitted to the script IF the form's method was POST. (ie: <form method="POST" action="a.php">) In all other respects, $_GET and $_POST behave exactly the same way, but if the form submitted used the GET method, $_POST will be empty.

8.2 Reading form parameters in your PHP script

Once you've determined which type of request is being used to send information to your script, actually reading the information in PHP is simple - merely look in the appropriate system array for the item. For example, the item named data submitted with a GET type request would be in $_GET["data"], and the same form item in a POST type request would be in $_POST["data"] instead. The main difficulty occurs when you are making a script which might be accessed through either GET or POST interchangeably - in this situation, you must first find the information being submitted, and then store it more easily for use. Below is an example of a PHP script attempting to read a form item called data, where the type of request is not initially known:

if ($_POST["data"]) { $fData = $_POST["data"]; } else { $fData = $_GET["data"]; };

In the above example, we use an IF statement to check and see if any information exists in the variable $_POST["data"] - if this variable exists, and has something in it, then it will result in the condition being true - if the variable in the brackets does not exist, or is empty, it will result in a condition of false. Thus, we can use it as the condition for the IF statement, and get our data from the appropriate array. If neither array contains the data, then which one we retrieve $fData from does not matter - an empty variable from one location is just as empty as an empty variable from another. If we are concerned about there actually being a value inside of the $fData variable afterwards, we can simply add this code after the previous block:

if ( !($fData) ) { // do whatever you need to fix the missing data: $fData = "default value"; };

The ! means "not", and makes the condition only true if whatever is after it is false. ("!(false)" is the same as "true") This lets you have your script deal with the required information being missing in whatever manner you feel is appropriate - either by setting your own default values, or by sending an error back to the user telling them that they forgot to give you some important information.

Another thing we can do is have our script process all of the items received from a form and display them to us, like this:

<html> <head> <title>Display Form Items</title> </head> <body> <table> <tr><th>Name</th><th>value</th></tr> <?php foreach ($_POST as $key => $value) { print ("<tr><td> $key </td><td> $value </td></tr>"); }; ?> </table> </body> </html>

This script will just display back all items in any form submitted to it. The foreach loop is a special loop that goes through an array, and runs the contents of the loop once for each entry in the array. In this case, that would be once for each item in the submitted form. (The following form submits to the script below, to demonstrate what it's output will look like:

thatItem: thatSelect:

An important thing to note here is that the form item names are case sensitive. This means that if your form item's name is "ThEiTeM", then inside of the script, it will only be accessible as "ThEiTeM" as well, and if you write a script for that, then change your form to use "TheItem" instead, your script will stop working! Below is an example of a script that reads in one item - a user's name - and expects the form item to be called "name". As long as we submit our form items properly, this will work fine, but if we submit it as "Name" instead, the script won't see it:

<html> <head> <title>Display Form Items</title> </head> <body> <p> <?php $whatever = $_POST["name"]; print(" Your name is: $whatever "); ?> </p> </body> </html>

And below are two forms - one with an input named "name", the other with an input named "Name". The only difference is the capitalization of the first letter of the name, yet one works, and the other doesn't.

<form name="goodName" method="post" action="php/testCase.php"> name: <input type="text" name="name" value="" /> <input type="submit" name="submit" value="submit" /> </form><br />
name:
<form name="badName" method="post" action="php/testCase.php"> Name: <input type="text" name="Name" value="" /> <input type="submit" name="submit" value="submit" /> </form><br />
Name:

This is yet another example of why paying careful attention to the case of letters in web programming is very important. Even if your company has hired someone else to write all of the server side scripts for you, making the HTML that interacts with them requires that you pay close attention to details.

9: Changing the HTTP Headers

Occasionally you may want to have your script do something special - be it delivering a file that is not HTML, or sending the browser away to some other location. Doing these things requires that you alter the HTTP Header that is sent out by the web server. To help with this, PHP has a special command for you to use: Header. This command lets you print out new HTTP headers to be added to the list the server is already printing out.

9.1 Content Type

By default, the headers from the server will always include a Content-Type: text/html line, which tells the browser that the new file is an HTML file and to display it as such. If we change that line, we can make the browser display the HTML source code, like this:

<?php Header("Content-type: text/plain"); ?> <html> <head> <title>Display Form Items</title> </head> <body> <p>Wheee! </p> </body> </html>

Similarly, if we wanted to output a jpeg image, we could set the Content-type: header to image/jpeg, and the browser would interpret the resulting output as if it was the contents of a Jpeg image. (Note: The output in that case should actually be the contents of a Jpeg image - if you try outputting a regular HTML file like above with the wrong type, this will be the result.

9.2 Redirecting the Browser

Another task that can be accomplished with HTTP headers is to move the browser to a different location, with the Location: header - just give it a URL as it's value, and the browser automatically goes on to a different page instead of displaying the current one, like this:

<?php Header("Location: /60-270/index.php"); ?> <html> <head> <title>Display Form Items</title> </head> <body> <p>Wheee! </p> </body> </html>

In this example, our Location: header tells the browser to go to the file index.php - the URL given here gets the same rules applied to it as any HTML link in an <a> tag. As far as the browser is concerned, the page you tried to visit never even existed, so even the back button and history list in the browser won't mention it.

9.3 "Meaningless" Headers

Remember that not all HTTP headers have meaning to the browser - for example, if we want to send out our own custom header from our PHP script, we can do so, and it will not effect the browser at all, like this:

<?php Header("FavouritePet: Dog"); ?> <html> <head> <title>Display Form Items</title> </head> <body> <p>Wheee! </p> </body> </html>

The only way we would be able to tell that the new header was there would be if we used the telnet program to connect directly to the web server, and entered the commands to view the page manually, like this:

GET /60-270/php/header-04.php HTTP/1.0 HTTP/1.1 200 OK Date: Wed, 10 Nov 2004 22:15:00 GMT Server: Apache X-Powered-By: PHP/4.3.4RC1 FavouritePet: Dog Connection: close Content-Type: text/html <html> <head> <title>Display Form Items</title> </head> <body> <p>Wheee! </p> </body> </html> Connection closed by foreign host.

While this may be of no practical value in most cases, if you have written your own web browsing program, it is possible to use this method to deliver extra content or features to your own browser without harming or even affecting how other browsers see the web page they are given.