Solved

cgi upload file and count words

Posted on 2003-11-17
13
407 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
Comment Utility
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
Comment Utility
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
Comment Utility
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
 

Author Comment

by:Nicholas Niggel
Comment Utility
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
Comment Utility
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
Comment Utility
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
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 18

Expert Comment

by:kandura
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
   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
Comment Utility
kandura That's what I needed.

Thanks for all the Help.

0

Featured Post

Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

Join & Write a Comment

I have been pestered over the years to produce and distribute regular data extracts, and often the request have explicitly requested the data be emailed as an Excel attachement; specifically Excel, as it appears: CSV files confuse (no Red or Green h…
Checking the Alert Log in AWS RDS Oracle can be a pain through their user interface.  I made a script to download the Alert Log, look for errors, and email me the trace files.  In this article I'll describe what I did and share my script.
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…
Illustrator's Shape Builder tool will let you combine shapes visually and interactively. This video shows the Mac version, but the tool works the same way in Windows. To follow along with this video, you can draw your own shapes or download the file…

744 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

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now