Solved

cgi upload file and count words

Posted on 2003-11-17
13
428 Views
Last Modified: 2010-03-04
Hello
I am a student working on homework. Prob is get a file with cgi from html page, upload file and count words, display results. I'm sure its a common hw prob but I am stuck. Also, have checkbox to upload automatically a file for testing "raven.txt" if checked

Any help much appreciated, please explain my mistake.
cgi is below also html below that

!/usr/bin/perl
#file: upload.pl

use CGI qw/:standard/;

print header,
    start_html('Word Counter'),
    h1('Word Counter');

print_form()    unless param;
print_results() if param;
print end_html;

sub print_form {
    print start_multipart_form(),
       filefield(-name=>'upload',-size=>60),br,
       submit(-label=>'Upload File'),
       end_form;
}

sub print_results {
    my $length;
    my $file = param('upload');
    if (!$file) {
        print "No file uploaded.";
        return;
    }
    print h2("File name\n"),$file;
    my $lines = 0;
    my $words = 0;
    my @words;
    my @output;
    @lines = @_;
    foreach (@lines){
            $lines++;
             @words = split;
             foreach(@words){
                     $words++;
             }
    }
    print "<br><b>Number of Lines:</b> $lines <br>\n";
    print "<b>Number of Words:</b> $words <br>\n";

}

#     html  

<html>
<title>Basic Word Counter</title>
<body>
<h1>Word Counting Program</h1>
What file would you like to process
<form action="/cgi-bin/word.cgi" method="post" enctype="multipart/form-data">
File Name:
<br>
<input type="file" name="upload" size="40">
<br>
<br>
<input type="reset" label="RESET">
<input type="submit" name=".submit" value="Count Words">
<input type="hidden" name=".cgifields" value="raven">
<br><br>
<input type="checkbox" name="raven" value="on">
Or choose
<a href="raven.txt">The Raven</a>
</form>
</body>
</html>
0
Comment
Question by:Nicholas Niggel
  • 7
  • 6
13 Comments
 
LVL 18

Expert Comment

by:kandura
ID: 9768161
Where do you get your lines from? And where did you _expect_ them to come from?
Once you find the difference between those two, you will have your answer :-)

Kandura
0
 

Author Comment

by:Nicholas Niggel
ID: 9768238
OK while you where answering I did this with $ARGV it now counts choosen file
What about the checkbox for auto uploading?

#!/usr/bin/perl
#file: upload.pl

use CGI qw/:standard/;

print header,
    start_html('Word Counter'),
    h1('Word Counter');

print_form()    unless param;
print_results() if param;
print end_html;

sub print_form {
    print start_multipart_form(),
       filefield(-name=>'upload',-size=>60),br,
       submit(-label=>'Upload File'),
       end_form;
}

sub print_results {
    my $length;
    my $file = param('upload');
        if (!$file) {
      $file="raven.txt";
      open(FILE, "$file") || die "Cannt: $!\n";
      while (<FILE>) {
        $lines{$ARGV}++;
        @words = split(/\W+/);
        $count{ARGV} += @words;
      }
      foreach $linecount (sort keys %lines) {
          print h2('File Lines'), $lines{$linecount};
      }
      foreach $wordcount (sort keys %count) {
          print h2('File Words'), $count{$wordcount};
      }
    }
    else {
         while (<$file>) {
           $lines{$ARGV}++;
           @words = split(/\W+/);
           $count{$ARGV} += @words;
        }
        foreach $linecount2 (sort keys %lines) {
            print h2('File Lines'), $lines{$linecount2};
        }
        foreach $wordcount2 (sort keys %count) {
            print h2('File Word'), $count{$wordcount2};
        }
    }
       
}

0
 
LVL 18

Expert Comment

by:kandura
ID: 9768304
very good :-)

yes, how about that checkbox...
You have to add it to your form of course, so the user can see it, and check it if they want.
Then you will have to check if it has been selected, and act accordingly.
0
PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

 

Author Comment

by:Nicholas Niggel
ID: 9818175
kandura - you still out there ? Or anyone else ?
Can you take a look at this and give me a pointer as to why my print_raven doesn't count words or lines ?


#!/usr/bin/perl

use CGI ':standard';
use CGI::Carp 'fatalsToBrowser';

print_form() unless param;
print_results() if param ('upload');
print_raven() if param ('The Raven');
print end_html;

sub print_form {
     print header;
     print start_html(-title=>'Basic Word Counter');
     print h1("Basic Word Counter");
     print start_multipart_form();
     print "Please upload a file";
     print br;
     print filefield(-name=>'upload', -size=>40);
     print br;
     print checkbox(-name=>'The Raven');
     print br;
     print br;
     print submit(-label=>'GO');
     print reset;
     print endform;
}

sub print_results {  
    my $file = param('upload');
    print header;
    print start_html;
    print h1("The file you selected has:");
    print br;
    while (<$file>) {  
       $lines{$ARGV}++;
       @words = split(/\W+/);
       $count{$ARGV} += @words;
    }
    foreach $linecount2 (sort keys %lines) {
        print h2('File Lines'), $lines{$linecount2};
    }
    foreach $wordcount2 (sort keys %count) {
        print h2('File Word'), $count{$wordcount2};
    }
   print h2('File Name'), $file;
}    

sub print_raven {
    my $file = 'raven.txt' ;
    print header;    
    print start_html;
    print h1("The Raven has:");
    print br;
    while (<$file>) {
       $lines++;
       @words = split(/\W+/);
       $count += @words;
    }
    foreach $linecount2 (sort keys %lines) {
        print h2('File Lines'), $lines{$linecount2};
    }
    foreach $wordcount2 (sort keys %count) {
        print h2('File Word'), $count{$wordcount2};
    }
   print h2('File Name'), $file;
}
0
 
LVL 18

Expert Comment

by:kandura
ID: 9818262
That's because you do not have the hashes %lines or %count.
The number of lines is in $lines and the word count is in $count.

So remove the two foreach blocks from print_raven and add instead:

   print h2('File Lines'), $lines;
   print h2('File Word'), $count;
0
 

Author Comment

by:Nicholas Niggel
ID: 9818346
Thanks for getting back to me.
I see my use of the hashes instead of scaler(thanks for pointing that out), but I tried your suggestion and it still doesn't show a number count for words and lines.
Is this correct:

   while (<$file>) {
       $lines++;
       @words = split(/\W+/);
       $count += @words;
    }
I have the file raven.txt in the same directory.
0
 
LVL 18

Expert Comment

by:kandura
ID: 9818513
Yes, that looks about ok. However, there may be a problem opening the file. Make sure that the webserver user has permission to read it.

Try opening it explicitly to see if that's the problem:

sub print_raven {
    my $file = 'raven.txt' ;
    print header;    
    print start_html;
    print h1("The Raven has:");
    print br;
    open F, "$file" or print "<b>Error opening $file: $!</b><br>";      # <---- this might give you a clue
    while (<F>) {
       $lines++;
       @words = split(/\W+/);
       $count += @words;
    }
    close F;
 
   print h2('File Lines'), $lines;
   print h2('File Word'), $count;
   print h2('File Name'), $file;
}
0
 

Author Comment

by:Nicholas Niggel
ID: 9818609
Well that did the trick. It works with that.
must have been this

open F, "$file"

I was trying to read the file without opening it. Do I need to open it with an open statement first ?
0
 

Author Comment

by:Nicholas Niggel
ID: 9818642
How about this.
WHen I hit the GO button without selecting a file and without checking the checkbox. I get an error

Error message:
Premature end of script headers: word.cgi

it should just call the print_form() routine from this
print_form() unless param;

Any ideas ?
0
 
LVL 18

Expert Comment

by:kandura
ID: 9818717
About opening: yes, in this case you should. The upload field gives you an already opened filehandle to the uploaded file.

About form: I think the submit button also sends a parameter (usually its name). The best thing you can do is check if the form was posted.
If it wasn't, chances are that $ENV{'REQUEST_METHOD'} eq 'GET', while it will definitely be 'POST' when the form was submitted.
Otherwise, check on the explicit parameters you need.
0
 

Author Comment

by:Nicholas Niggel
ID: 9818985
The form is a post. Would I check this in the cgi by looking for a param ? like

print_form() if param ('GO');
I tried that and no good.

I thought that
print_form()    unless param;  
would do it
0
 
LVL 18

Accepted Solution

by:
kandura earned 200 total points
ID: 9819340
   print_form()    unless param;
will work; it will print the form when the script is requested without any parameters.

However, if soneone submits the form without setting a filename or checking the 'raven' box,
then your script will do this:

print_form() unless param;                # skipped because of .submit param (from the submit button)
print_results() if param ('upload');       # skipped because no file selected
print_raven() if param ('The Raven');   # skipped because not checked
print end_html;

So you're missing the HTTP header and the start_html in this case.

I suggest you move the
    print header;    
    print start_html;
from every subroutine, and add it at the top of your script:

    print header;    
    print start_html;
   
    print_form() unless ( param('upload') or param('The Raven') );   # <------ note that now we print the form if nothing was filled in
    print_results() if param ('upload');
    print_raven() if param ('The Raven');
    print end_html;
0
 

Author Comment

by:Nicholas Niggel
ID: 9819404
kandura That's what I needed.

Thanks for all the Help.

0

Featured Post

Netscaler Common Configuration How To guides

If you use NetScaler you will want to see these guides. The NetScaler How To Guides show administrators how to get NetScaler up and configured by providing instructions for common scenarios and some not so common ones.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

On Microsoft Windows, if  when you click or type the name of a .pl file, you get an error "is not recognized as an internal or external command, operable program or batch file", then this means you do not have the .pl file extension associated with …
A year or so back I was asked to have a play with MongoDB; within half an hour I had downloaded (http://www.mongodb.org/downloads),  installed and started the daemon, and had a console window open. After an hour or two of playing at the command …
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…

825 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question