Server Side Programming

Before Javascript, the only way to make your web application interactive and dynamic was to use forms and have a program that worked with your web server generate HTML on the fly. This is one of the most important ideas in web programming. We don’t have to limit our thinking about a web server returning the contents of a static file. It is all just text after all, so it does not have to come from a file, it could just as well be generated by a bunch of print statements in a program.

In fact that will be our starting point. All the other web development work since the mid 1990’s has been to improve upon the idea that a web page can be generated from some print statements.

Lets look at a hello world style example.

This should be pretty self explanatory. When you run this program it generates the text that looks just like the text you might find in a file named hello.html.

Now the next question is to ask how does this happen? How can I get this hello program to generate code and serve my own browser? The first thing you need to do is create a folder called www. In the www folder make a second folder called cgi-bin and place create a file in that folder.

From the command line make sure that you are in the www folder and run the following command:

python3 -m http.server --cgi 8000

Then in your browser open the url: http://localhost:8000/cgi-bin/

When the web server sees a URL that is in the cgi-bin folder it knows that instead of just returning the contents of the file, it should execute the program and direct the output from that program back to the browser. Cool right?!

The program can be as complicated as you want, as long as the output of the program comprises html that constitutes a complete web page.

Exercise: Write a program that calculates the first 25 fibonacci numbers and displays the output in a table.

Next Section - Processing user Input