CGI and Perl

Example 2: Open a New Browser Window

Ever wonder how you could open a new browser window? This simple example in Listing 5.2 illustrates how CGI.pm can be used to generate a form with a target element that points to a new window. When you click the button on the first page, a new window some_target is opened to display the output in the else clause. The output from Listing 5.2 is shown in Figure 5.4.

Listing 5.2. Open a new browser window

#!/usr/local/bin/perl
 use CGI;
 $query = new CGI;
 print $query->header;
 print $query->start_html(`New Window');
 if (!$query->param) {
     print $query->startform(-target=>`some_target');
     print $query->submit(`Action','New Browser Window');
     print $query->endform;
 } else {
     print "<H1>Here's your new window!</H1>\n";
 }
 print $query->end_html;

The output from Example 2
Figure 5.4. The output from Example 2.

Example 3: Upload a File to the Server

Listing 5.3 shows how CGI.pm and CGI::Carp can be used with Netscape 2.0+ browsers to make possible the transfer of files from the browser to the server. CGI.pm is used to set up a multipart form that accepts the data in the file. Then the filefield() returns a file upload field that causes a window on the remote browsers machine to be created, prompting them for a file to transfer. The filefield() has the following parameters:

print $query->filefield(-name=>`uploaded_file',
                         -default=>`starting value',
                         -size=>50,
                         -maxlength=>80);

where -name is the name for the field. The other parameters are optional. The -default parameter specifies the starting value for the file name. The -size parameter is the size of the field in characters. The -maxlength parameter is the maximum number of characters the filefield may contain.

After the file is transferred to the server, the filename entered can be determined by calling param():

$filename = $query->param(`uploaded_file');

where uploaded_file is whatever you called the upload field. The file can be accessed normally or as a filehandle:

# Read a text file and print it out
         while (<$filename>) {
            print;
         }
 # Copy a binary file to somewhere safe
         open (OUTFILE,">>/usr/local/web/users/feedback");
         while ($bytesread=read($filename,$buffer,1024)) {
            print OUTFILE $buffer;
         }

Listing 5.3 shows an example of the File Upload field in action, the output of which is shown in Figure 5.5.