Making a simple guestbook

      In this how-to, we will learn how to write to a file, using data from a form.

      To create our guestbook, we will use one file that has "entries" in it. It will be called guestbook.html and will look like this:

      <HR>
      This is an entry in the guestbook<BR>
      <BR>
      Thank You<BR>
      <BR>
      <B>John Doe<BR>
      Anytown, USA</B>
      <HR>
      This is another entry.<BR>
      <BR>
      Bye<BR>
      <BR>
      <B>Jane Doe<BR>
      Bigtown, USA</B>
      

      The <HR> seperates each entry, and each line will end in a <BR>. The entries are "signed" at the bottom in bold. We will also create the form for adding an entry in the guestbook:

      <FORM METHOD=POST ACTION="/cgi-bin/guestbook.pl">
      Name:<INPUT NAME="name"><BR>
      Location:<INPUT NAME="location"><BR>
      <BR>Comments:<BR>
      <TEXTAREA NAME="comments">
      </TEXTAREA>
      <INPUT TYPE="SUBMIT">
      </FORM>
      
      

      Now we will write the script to do the magic

      #!/usr/bin/perl
      
      #full path for the guestbook file
      $file="/home/httpd/html/guestbook.html";
      
      require "cgi-lib.pl";
      &ReadParse;
      
      #translate all the linefeeds into <BR>s for nice formatting
      $in{'comments'} =~ s/\n/<BR>\n/g;
      
      #open the guestbook file and append data to the end of it
      open(GUESTBOOK,">>$file");
      
      #print the information
      print GUESTBOOK "\n<UL>\n";
      print GUESTBOOK $in{'comments'};
      print GUESTBOOK "\n<B>$in{'name'}<BR>\n";
      print GUESTBOOK "$in{'location'}</B><BR>\n";
      
      close GUESTBOOK;
      

      All this script does is open the guestbook.html file and add the comments from the form (with some nice html formatting). Lets note a few things in this script:

      1. We must know the full path name in order for the file to be opened. You can figure out where this is by typing "pwd" in the directory that contains this file.
      2. The script must also have permission to write to the file. The easiest way to do this is to type "chmod 666 guestbook.html" which will allow any user to write to the file.
      3. There is some weird Perl syntax for doing a translation. This uses the special "s" operator to to a find/replace. It replaces all instances of \n with a <BR>\n. This puts a <BR> after every line, which makes the entry in the html file look the same as it did in the textbox when the user typed it in.
      4. We opend the file "guestbook.html" in append mode. This will take anything printed to the file and append it to the end, which is what we want for a guestbook.
      5. The word GUESTBOOK is called a File Handle. It is actually a number which refers to an open file (it can also be used for a pipe, or socket as we will see later). We can think of it as a nickname for telling "print" where to put the data.


      Contents