Solved

help ! write and read to file

Posted on 1998-12-01
13
320 Views
Last Modified: 2010-03-04
let say I have 'enter.html' and 'view.html'.

In enter.html, there is a textfield for name and two button for submit and clear. User should enter his or her name in that textfield, the press submit. Then his or her name will be stored in the text file called 'name.txt'

In view.html, user can see how many name already in the name.txt and print those name out on the screen one by one.


I would like to use perl to write this program but I don't have any clues and I am new to perl , so I am asking experts, please give me a complete code and explanation of the code. Thank you !
0
Comment
Question by:tanc02
  • 7
  • 6
13 Comments
 
LVL 1

Expert Comment

by:squimph
ID: 1206661
#!/usr/bin/perl

use CGI qw/:standard/; # Use CGI.pm's standard functions

$namefile = '/tmp/name.txt'; # Name and location of file to store the names in

print header; # Print the 'content-type' header required by all CGI scripts.

# Decide whether to show the 'enter name' form, the 'list of names' form,
# or store a name in the name file:

# If parameter 'name' exists, this script must have been
# called from the 'enter name' form, so we should stick the name in a file:
if ( param('name') ) {
    store_name();
    show_thanks();
}
elsif ( param('mode') eq 'view' ) {
    show_view_form()
}
# Otherwise, just print out the 'enter name' form:
else {
    show_enter_form()
}

print end_html;
exit;

# Subroutines:

sub store_name {
    # Add the name to the end of the file:
    open NAMEFILE, ">>$namefile" or die; # Open the file in append mode
    print NAMEFILE param('name'),"\n"; # Print name and a newline to file
    close NAMEFILE; # close the file
}

sub show_view_form {
    print h1('List of names'),p; # Print a nice page heading
    # Print the contents of the name file
    open NAMEFILE, "<$namefile" or die; # Open in read-only mode
    while ( $linein = <NAMEFILE> ) {
        chomp  $linein; # remove trailing newline if there is one
        print "Name = $linein", p, "\n";    # Print the line to the web browser
    }
    close NAMEFILE;
}

sub show_enter_form {
    print h1('Name entry form');
    print start_form;
    print "Enter name: ", textfield('name'),p;
    print submit;
    print end_form;
}

sub show_thanks {
    # Displays a thank you message
    print h1('Thank you');
    print 'Thank you for submitting your name',p;
    print "<A HREF=$myself?mode=view>View names</A>";
}
0
 
LVL 1

Expert Comment

by:squimph
ID: 1206662
Comments for the above script:

- This script does everything using just one CGI script. Store the above in a file in your web server's CGI-BIN called 'readwrite.pl' Run it by going to URL http://your.server.name/cgi-bin/readwrite.pl

- You may need to change the line
    #!/usr/bin/perl
  ...in the script to point to the location of perl on your system (sometimes it's /usr/local/bin/perl)

- The script creates the names.txt file in the /tmp directory but you should change it to a more private directory. Whatever directory you choose must be able to be written to by your web server.

- This script uses CGI.pm, a perl library that comes standard with Perl 5. With CGI.pm you can do everything just with one CGI program... generate the HTML forms, and store and retreive names from the file by running it different ways. (see http://www.genome.wi.mit.edu/ftp/pub/software/WWW/cgi_docs.html for the details about CGI.pm )

- I've put as many comments as I could in the above code... once you read about CGI.pm it hopefully won't need a lot more explanation.
0
 
LVL 1

Author Comment

by:tanc02
ID: 1206663
I have cgi-lib.pl but i don't have CGI.pm and I tried to get CGI.pm and I think it is
difficult for me to install and download since I have no idea at all. Could you write this script in perl only ?
0
 
LVL 1

Expert Comment

by:squimph
ID: 1206664
It's well worth the trouble to get and install CGI.pm ... if you're going to learn how to write CGI scripts, doing it without CGI.pm is just plain painful. Most CGI scripts you download on the Internet require it.

If you're using a Unix machine, it's easy to get and install. But, if you really insist on a plain jane perl version, reject the above answer so I can post another one.
0
 
LVL 1

Author Comment

by:tanc02
ID: 1206665
Thank a lot, I hope I am not giving trouble to you
0
 
LVL 1

Accepted Solution

by:
squimph earned 200 total points
ID: 1206666
Okay... here you go. It's ugly without CGI.pm but it works. Note in this version you have to edit the line that begins '$myself =' to point to the URL of the script itself.


#!/usr/bin/perl

$namefile = '/tmp/name.txt'; # File to store the names in
$myself = '/cgi-bin/readwrite.pl'; # EDIT THIS TO BE THE URL of this script

print "Content-type: text/html\n\n"; # Print the header required to be first line of all CGI scripts.

print "<HTML><HEAD><TITLE>Name entry</TITLE></HEAD>\n";
print "<BODY>\n";

# Since we can't use CGI.pm, we have to gather form input
# variable the old fashioned way:
parse_form();

# Decide whether to show the 'enter name' form, the 'list of names' form,
# or store a name in the name file:

# If parameter 'name' exists, this script must have been
# called from the 'enter name' form, so we should stick the name in a file:
if ( $param{'name'} ) {
        store_name();
        show_thanks();
}
elsif ( $param{'mode'} eq 'view' ) {
        show_view_form()
}
# Otherwise, just print out the 'enter name' form:
else {
        show_enter_form()
}

print "</BODY></HTML>";
exit;

# Subroutines:

sub parse_form {
        # Break form input into a hash and un-HTML-ize it:
        # (Shamelessly pilfered from Matt Wright's formmail.pl)
        # Break the input apart at the ampersands:
        if ($ENV{'REQUEST_METHOD'} eq 'GET') {
                @pairs = split(/&/, $ENV{'QUERY_STRING'});
        }
        elsif ($ENV{'REQUEST_METHOD'} eq 'POST') {
                read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'});
                @pairs = split(/&/, $buffer);
        }
        else {
                die 'Invalid request method from form';
        }
        # Now split name=value pairs at the equals sign, change
        # plus signs to spaces and othersize un-URL the input:
        foreach $pair (@pairs) {
                ($name, $value) = split(/=/, $pair);
                $name =~ tr/+/ /;
                $name =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
                $value =~ tr/+/ /;
                $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
                # Stuff the result into a hash called 'param':
                $param{$name} = $value;
        }
}

sub store_name {
        # Add the name to the end of the file:
        open NAMEFILE, ">>$namefile" or die; # Open the file in append mode
        print NAMEFILE $param{'name'},"\n"; # Print name and a newline to file
        close NAMEFILE; # close the file
}

sub show_view_form {
        print "<H1>List of names</H1><P>\n"; # Print a nice page heading
        # Print the contents of the name file
        open NAMEFILE, "<$namefile" or die; # Open in read-only mode
        while ( $linein = <NAMEFILE> ) {
                chomp  $linein; # remove trailing newline if there is one
                print "Name = $linein<P>\n";    # Print the line to the web browser
        }
        print '<A HREF="', $myself, '">Enter more names</A>';

        close NAMEFILE;
}

sub show_enter_form {
        print "<H1>Name entry form</H1>\n";
        print "<FORM METHOD=POST ACTION=$myself>\n";
        print "Enter name: <INPUT NAME=name></P>\n";
        print "<INPUT TYPE=SUBMIT>\n";
        print "</FORM>\n";
}

sub show_thanks {
        # Displays a thank you message
        print "<H1>Thank you</H1>\n";
        print "Thank you for submitting your name.<P>\n";
        print "<A HREF=$myself?mode=view>View names</A>\n";
}

0
What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

 
LVL 1

Author Comment

by:tanc02
ID: 1206667
I got an 500 internet error. Here is what I did :

readname.pl and name.txt store in /home/mcs436-2/web-server/cgi-bin
and I have changed only two lins taht you told me.

$namefile = '/home/mcs436-2/web-server/cgi-bin/name.txt'; # File to store the names in
$myself = '/home/mcs436-2/web-server/cgi-bin/readwrite.pl'; # EDIT THIS TO BE THE URL of this script

What is the problem ?
0
 
LVL 1

Expert Comment

by:squimph
ID: 1206668
'500 internal error' usually means there's a syntax error in the script or perl cannot be found. But before we tackle that problem...

- Rename the file to 'readwrite.pl' (it has to be exactly the same name as referred to in the $namefile variable)

- Make readwrite.pl executable... eg. do a 'chmod 755 readwrite.pl'

- Move name.txt to some other directory. Data files should *never* go into CGI-BIN for security reasons. Most people create a '/data' directory for their CGI's data files. Don't forget to modify the $namefile variable to point to the new location. Make sure the file can be written to by the web server.

Okay... now to deal with that '500' error:

- Can you run the script yourself from the command line? eg. go to cgi-bin and type './readwrite.pl'  It should spit out something like this:

 Content-type: text/html
 <HTML><HEAD><TITLE>Name entry</TITLE></HEAD>
 <BODY>
 Invalid request method from form at ./readwrite.pl line 49.

If you can't run the script from the command line, your web server won't be able to run it either.

- If get a message like 'syntax error' when you try to run the script, carefully check the script for errors such as one line wrapped across two, etc. The error message will usually give the line number of the error.

- If you an error like 'No such file or directory' you probably have to edit the first line of the script to point to the location of Perl on your system. 'whereis perl' might help you it. For example, if perl is located in the /usr/local/bin directory on your system, change the first line of the script to read:

   #!/usr/local/bin/perl

- Lastly, if you can run the script from the command line, but the web server still gives a '500' error, look in the web server's error log for clues as to why. Usually error messages will be recorded there.
0
 
LVL 1

Author Comment

by:tanc02
ID: 1206669
After I ran it on the command line I saw ( I entered this  'perl readwrite.pl' on the commane line)

Content-type: text/html
 
<HTML><HEAD><TITLE>Name entry</TITLE></HEAD>
<BODY>
Invalid request method from form at readwrite.pl line 49.



and in the error_log file, I have :

[Wed Dec  2 14:48:28 1998] access to /home/mcs436-2/web-server/cgi-bin/readwrite.pl failed for 199.17.35.90, reason: Premature end $ end of script headers

do you have any clue
0
 
LVL 1

Expert Comment

by:squimph
ID: 1206670
Looks like your web server is not set up to run perl. Have you ever run any other perl CGI script on your web server before?

But before we get into that... we've now left the original "how do I do this in perl" question and entered a totally new question: how to install a CGI script on your web server.

I've provided two scripts that do what you originally asked (they both work, trust me) but it looks like there's some work you have to do on your web server to get it to run perl CGIs. I can help you with that too, but not for the same measly 200 points (*grin*)

Seems to me you should accept the above answer, since your original question HAS been answered (twice!) then open another one about how to install a perl CGI script and configure your web server. In that new question, it would be helpful to describe which web server you're using (Apache? Microsoft IIS?) and on what platform (Linux? Windows NT?). Then I and others can help you get things set up correctly. Sound fair?
0
 
LVL 1

Author Comment

by:tanc02
ID: 1206671
I am taking web adminisration at st. cloud state university.
I am sure my configuration is correct 100% because I have ran so many complicated
perl script like guestbook and others, and I don't have any problem at all.
You tell me your script is correct, then can you tell where is URL that will execute
ose both script, if everything is fine, then I will give you the point.

*p/s : my professor don't know much about perl and any cgi script.
0
 
LVL 1

Expert Comment

by:squimph
ID: 1206672
One last time then:

You won't say what type of system you are using, but from the pathnames your using I'm going to assume it's Unix. These hints are only valid for a unix system:

- You ran the script from the command line just fine, but I see you used 'perl readwrite.pl' to run it. Try running it by typing only  ./readwrite.pl  (That's DOT FORWARD-SLASH).

- If you get 'no such file or directory' it means the first line of the script is not pointing to the location of perl on your computer. As mentioned above, make sure the line #!/usr/bin/perl points to the perl executable on your system. If your other perl scripts work, adjust the first line in readwrite.pl to match the location of perl used in the other scripts.

- If you get 'permission denied', the permissions on the script are wrong. Assuming you are on a Unix system, 'chmod 755 readwrite.pl' will set the correct permissions on the file.

If you can't run the program using ./readwrite.pl your web server won't be able to either.

- Try to run the script from your web browser (using something like http://your.web.server/cgi-bin/readwrite.pl but the URL you need to use depends on how you have your web server set up) If you get an error message, the last few lines of your server's error log will give clues as to what's wrong.

All the above are just basic Unix administration tasks and have nothing really to do with Perl or CGI.
0
 
LVL 1

Author Comment

by:tanc02
ID: 1206673
I got it already. The problem is on the first line.

I have an extra space in front on
#!/usr/bin/perl


Thank a lot from you.

I have another question, but you don't have to answer this

What should I do if I want to have another field for age.

Remeber, you don't have to answer this, but I will appreciated if you can teach me.

Thank you !

0

Featured Post

Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

Join & Write a Comment

I've just discovered very important differences between Windows an Unix formats in Perl,at least 5.xx.. MOST IMPORTANT: Use Unix file format while saving Your script. otherwise it will have ^M s or smth likely weird in the EOL, Then DO NOT use m…
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…
You have products, that come in variants and want to set different prices for them? Watch this micro tutorial that describes how to configure prices for Magento super attributes. Assigning simple products to configurable: We assigned simple products…

707 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