blank.gif
webreview.com - Cross-Training for Web Teams
Search for: 
Jump to:
blank.gif
blank.gif

 
 

A Songline PACE Production



Web Page Updates Through CGI

by Brent Michalski
July 24, 1998
 
 

Do you have a manager or user who needs to make frequent changes to a Web page, but doesn't know the first thing about HTML? This week we create a simple script that will make the manager look good, and you look like a genius. 
View the demo


View the demo.

Easy Page Updates 

I recently had a program manager ask me to redesign an internal Web site. One of the features he wanted was a What's New area on the home page that would be updated frequently. The What's New data was to come from the program manager, but he didn't know any HTML so his idea was to send me the changes and then I would be responsible for updating the page.

Well, I wasn't too keen on the idea of getting changes to the page on a daily basis, and having it be my head if they weren't done on time. To remedy this situation, I quickly told the program manager I could make a page that even he could easily update. That way, I told him, he could make changes whenever he felt like it and wouldn't have to wait for me to update the page. He bought the idea and this week's example script was born.

There are a couple of different approaches you could take to solve this problem:

  • You could have the script write to a text file, and have the calling page read that file and import the data. The drawback to this method is that the calling page needs to be a CGI script.
  • You could have the script create a text file, just like above, but use a Server Side Include (SSI) to read the data into the page. This won't work if SSIs are not enabled on your server.
  • Or, you could take the approach I did and just generate the entire page each time it is updated. This solves the CGI and SSI issues. We simply create a standard HTML file.

The Program 

For this script, I created a whimsical company and created the script for the president of the company. I am sure you will have a different person to write the script for.

Here are the pieces of this particular project:

  1. The script.
  2. The form.
  3. The new page generated by the script.
Below is the code with line numbers for you to look at.

The line numbers are not part of the program. If you want to see the program without the line numbers, click here. The line numbers simply make it easier for me to talk about the program.

1: #!/usr/bin/perl
2: use CGI qw/:standard :netscape :html3/;
3: $query = new CGI;
4: $PageLocation="data/homepage.html";
5: $message = $query->param('message');
6: $message =~ s/\015\012/<BR>/g;
7: &CheckForError;
8: &CreatePage;
9: &PrintResults;
10: exit;
11: ######################################
12: ## End of main program
13: sub CreatePage{
14:   open(PAGE,">$PageLocation") || die("Error $! opening file!");
15:   print PAGE<<HTML;
16: <HTML>
17: <HEAD>
18: <TITLE>ABC Virtual Paper Company</TITLE>

20: </HEAD>
21: <BODY BGCOLOR="#FFFFFF">
22: <P ALIGN="CENTER"><B>
23: <FONT FACE="Arial, Helvetica, sans-serif" SIZE="4">
        ABC Virtual Paper Company<BR>
24:   </FONT></B><FONT FACE="Arial, Helvetica, sans-serif" SIZE="3">
25: <B>Home Page</B>
26: </FONT></P>
27: <TABLE BORDER="0" WIDTH="75%" ALIGN="CENTER" CELLSPACING="0">
28:   <TR>
29:   <TD BGCOLOR="e0e0e0">
30:   <P><FONT FACE="Arial, Helvetica, sans-serif" SIZE="2">
31:   Welcome to the ABC company home page. We are here to provide
32:   you with all of your virtual paper needs. We have virtual 
33:   paper in all sizes, thicknesses and colors.</FONT></P>
34:   <P><FONT FACE="Arial, Helvetica, sans-serif" SIZE="2">
35:   Our commitment is to provide you with the best virtual paper
36:   available. Our virtual paper undergoes rigorous virtual
37:   testing before we deliver it to our customers.</FONT></P>
38:   <P><FONT FACE="Arial, Helvetica, sans-serif" SIZE="2">
39:   There are others out there offering virtual paper at 
40:   wholesale prices, but our quality is virtually hard
41:   to beat. In fact, if you are not virtually satisfied 
42:   with our virtual paper, we will send 10x your 
43:   virtual order to you free!</FONT></P>
44:   <P><FONT FACE="Arial, Helvetica, sans-serif" SIZE="2">
45:   With all of that going for us, it is hard to imagine
46:   anyone wanting to make their virtual paper purchases 
47:   from any other virtual company. Thank you for choosing 
48:   the <B>ABC Virtual Paper Company.</B></FONT></P>
49:   </TD>
50:   </TR>
51:   <TR>
52:   <TD BGCOLOR="c8c8c8">
53:   <DIV ALIGN="CENTER">
        <B><FONT FACE="Arial, Helvetica, sans-serif" SIZE="2">
54:   A message from ABC's virtual president:</FONT></B> </DIV>
55:   </TD>
56:   </TR>
57:   <TR>
58:     <TD BGCOLOR="e0e0e0">
59:       <TABLE BORDER="1" WIDTH="85%" ALIGN="CENTER" CELLSPACING=0>
60:         <TR>
61:           <TD>
62:             <FONT FACE="Arial, Helvetica, sans-serif" SIZE="2">
63:      $message
64:             </FONT>
65:           </TD>
66:         </TR>
67:       </TABLE>
68:      </TD>
69:   </TR>
70: </TABLE>
71: <P ALIGN="CENTER">
72:  <FONT FACE="Arial, Helvetica, sans-serif" SIZE="2">
73:   [ <A HREF="homepage.html">Home</A>
74:   | <A HREF="homepage.html">Our Company</A>
75:   | <A HREF="homepage.html">Our Philosophy</A>
76:   | <A HREF="homepage.html">Our Vision</A>
77:   | <A HREF="homepage.html">Our Stuff</A>
78:   ]
79:  </FONT>
80:  <BR>
81:  <FONT FACE="Arial, Helvetica, sans-serif" SIZE="1">
82:   Note: These links don't work, they are just here for looks.
83:  </FONT>
84: </P>
85: </BODY>
86: </HTML>
87: HTML
88: close(PAGE);
89: return 1;
90: }
91: sub CheckForError {
92:   if ($message eq "") {
93:     print $query->header();
94:     $error_message =
        "<p>Field 'message' must be filled in.</p>\n";
95:     print $error_message;
96:     exit 0;
97:   } else {
98:     return 1;
99:   }
100: }
101: sub PrintResults {
102:   print $query->header();
103:   print $query->start_html('Great Work Sir'),
104:         p({-ALIGN=>'CENTER'},
105:          font({-FACE=>'ARIAL',-SIZE=>6},'Great Work Sir'),
106:          hr({-WIDTH=>'75%'})
107:         ), # Close the p
108:         table({-ALIGN=>'CENTER',-WIDTH=>'80%'},
109:          Tr(
110:           td(
111:            font({-FACE=>'ARIAL',-SIZE=>2},
112:             'Mr. President,
113:             <P>You have successfully changed the
114:             home page without any technical assistance!
115:             <P>Great work, you are a genius sir!'
116:            ), # Close the font
117:            p({-ALIGN=>'CENTER'},
118:             a({-href=>'data/homepage.html'},
119:              font({-FACE=>'ARIAL',-SIZE=>3},'View New Home Page')
120:             ) # Close the a
121:            )  # Close the p
122:           )   # Close the td
123:          )    # Close the tr
124:         )     # Close the table
125:        ;      # End the print statement
126:   print $query->end_html();
127: }

Line-by-Line Explanation 

Line 1: Tells the program where to find Perl on the Web server. This line will vary depending on where Perl is installed on your server so you need to make any necessary changes. On a UNIX server, this line is required. If you are running this program on an NT server, this line is not required but won't hurt anything if included. 

Line 2: Loads the CGI.pm module into the program. The arguments qw/:standard :netscape :html3/ bring in more functions for us to use in our program. These functions are all part of the CGI.pm module.

Line 3: Creates a new instance of the CGI object and calls it $query.

Line 4: Sets a variable called $PageLocation. This is the location and name of the page we are creating.

Line 5: Reads the input from the calling Web page and stores it in a variable called $message. This is the text the president entered into the form.

Line 6: This line takes whatever was sent in from message, removes the carriage return / line feed at the end of the lines, replacing them with the HTML tag <BR>.

The =~ is the binding operator in Perl. It tells Perl you want to perform the operation on the right side of the operator, on the variable that is on the left side.

The s/\015\012/<BR>/g is a Perl substitution operation, telling Perl to find the stuff in the first part, and substitute it with the stuff in the second part. In our case, we looked for \015\012 which are the octal values for the carriage return and line feed, and we replaced it with <BR>.

The g on the end of the operation tells Perl to do this globally. In English that means do this everywhere it is found. If we left the g off, Perl would only replace the first match it found.

Line 7: Calls the CheckForError subroutine which checks to make sure the required field(s) were filled in.

Line 8: Calls the CreatePage subroutine. This subroutine does the actual page creation.

Line 9: Calls the PrintResults subroutine. This subroutine simply gives the users some feedback and lets them know the page was created.

Line 10: Exits the program. We are actually done at this point! We did all of our work in the subroutines that follow.

Lines 11-12: Comments.

Line 13: Begins the CreatePage subroutine. This is the subroutine that creates the page.

Line 14: Opens the file we are creating. 

  • The name PAGE is called our filehandle. A filehandle is how we reference a file in our programs. By convention, filehandles are written as all UPPERCASE.
  • The ">$PageLocation" opens the filehandle using the filename stored in the variable $PageLocation for writing. The > tells Perl to open the filehandle for writing. If the file already exists, it overwrites the existing file with the new data. If the file does not exist, it creates a new one.
Lines 16-62: This is the first part of the HTML for the document. One tip here, create the entire HTML file you want to use in your favorite HTML editor and then copy it into this portion of your program. We are printing this block of text using a here document, so we can use a block of text without worrying about separate print statments, quotes or semi-colons at the end of each line.

Line 63: This is the $message variable we read in from the Web page. In here documents, you are allowed to use variables.

Lines 64-86: The rest of our HTML document. Nothing special, it is just HTML.

Line 87: Our closing string for our here document. Tells Perl to quit printing to the filehandle.

Line 88: Closes the PAGE filehandle that we opened in Line 14.

Line 89: Returns our program to the line after the one that called it. So we return and execute the code on Line 9.

Line 90: Ends our CreatePage subroutine.

Line 91: Begins our CheckForError subroutine. This subroutine verifies that the user entered data into the required areas on the calling Web page.

Line 92: An if statement that checks to see if the variable $message has anything stored in it. 

The eq in Perl means equal to when comparing strings. If you wanted to test for equality of numbers, you would use ==. Perl won't complain if you use eq to check numbers, but it will evaluate them as strings instead of numbers and you will not get the results you expected.

Line 93: The CGI.pm shortcut to print the HTTP header. This is a shortcut for: print "Content-type: text/html\n\n.

Line 94: Sets our error message variable to the text we want to send to the user. This is an extra step in this program, but I use this same subroutine commonly in other programs that have more than one variable passed in, so I left it alone.

Line 95: Prints the error message to the screen.

Line 96: Exits the program with a value of 0, indicating an error occurred.

Line 97: An else statement, if our $message variable was NOT empty, then we would do what is inside the else block.

Line 98: Returns us to the line after the line that called this subroutine, Line 8.

Lines 99-100: End our if..else block and close out the subroutine.

Line 101: Begins our PrintResults subroutine.

Line 102: Prints our HTTP header just like in Line 93.

Lines 103-125: These lines use some of CGI.pm's many shortcuts. Using these shortcuts can sometimes make your code harder to read, BUT they can save you a lot of typing. You have to decide if the trade-off is worth it. 

I am going to attempt to explain what the different lines do, but for a more detailed explanation, please go to the CGI.pm home page. Trying to go in depth about each item is beyond the scope of this article.

  • Line 103: start_html is a shortcut that prints out the HTML, HEAD, TITLE, and BODY tags. The text in quotes becomes the title of the page.
  • Line 104: p creates a Paragraph tag. The items in the curly braces {} are the attributes for our tags. For this tag, we make it ALIGN=>'CENTER'
  • Line 105: font creates a FONT tag. Notice here that I have attributes in the curly braces and follow them with a comma and some text. The text becomes "wrapped" by this tag so all attributes affect the text.
  • Line 106: hr is your everyday <HR> tag. We gave it a width of 75% here.
  • Line 107: ), This simply closed the p tag from Line 104.
  • Line 108: table begins the table we are going to use to center the text on the screen. We make it 80% wide and CENTER it.
  • Line 109: Tr begins a Table Row. Notice that the T is capitalized. This is done because Perl already has a tr function.
  • Line 110: td begins a TD block.
  • Lines 111-115: Another FONT tag with a couple lines of text. Notice that I put <P> tags right into the text. This is perfectly legal!
  • Line 116: ), Closes the FONT tag we created in Line 111.
  • Line 117: Creates another paragraph. This one we use to center our link back to the home page.
  • Line 118: a creates an A anchor tag. In this case we are creating a link to the "homepage.html" file.
  • Line 119: font This embeds a FONT tag inside of the a tag we started above. By doing this, I can control the font attributes of the link. This also contains the text that will be hyperlinked.
  • Lines: 120-125 These close all of the tags we had opened above, and finally the semi-colon ends the print statement from Line 103. I commented each one so that you could follow them easier. I could have put them all on one line, but it would not have been as easy for you to follow.
Line 126: Prints our closing HTML code using CGI.pm's end_html function. This is simply a shortcut in CGI.pm that prints out <BODY><HTML>.

Line 127: Closes the PrintResults subroutine.

Wrapping It Up 

This script is a very simple application that can make your life easier and aid your employers or customers who need to make changes to their pages. If you look at the code, we accomplish this with very little Perl code, around 50 lines.

Little applications like this can really make a difference on the site(s) you are responsible for. Not only do they save you time, they make your customers appreciate you more. I have found that the easier I can make the Web for my customers, the more they use it and appreciate it.

This type of application doesn't just have to be for people who don't know HTML. Write one for yourself that automates a page you frequently update. There are so many possibilities with even the simplest of programs, like this one. With a few modifications to this script, you could pass in another variable and update different pages based on what you passed in. So this script could then be used to update several pages, instead of just one.


Source Code for Web Page Updates Through CGI
View and download the source code for this week's article.
Next: CGI Troubleshooting Tips

Web Review copyright © 1995-99 Songline Studios, Inc.
Web Techniques and Web Design and Development copyright © 1995-99 Miller Freeman, Inc.
ALL RIGHTS RESERVED