Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I am using CGI-Application using Apache on Windows XP. I have a run mode setup so that I can open a page, slurp in a template into a textarea on a form, and then it's supposed to write the current info in the textarea to a file when the submit button is pushed. Here is the form field code:
<form name="mainform" action="webapp.cgi?rm=mode9" method="post"> <textarea name="text_field" cols="60" rows="20"><TMPL_INCLUDE NAME="me +nu.tmpl"></textarea> <br> <button type="submit">Update</button>&nbsp;&nbsp;&nbsp;&nbsp;<button t +ype="reset">Reset Form</button> </form>
here is the code for the save:
sub save_form { my $self = shift; # Get CGI query object my $q = $self->query(); my $record = $q->param( 'text_field' ); open( FH, '>output.txt' ) || die "Can't open output.txt: $!"; print FH $record; close ( FH ); # go back to the beginning return $self->run_mode( 'mode1' ); }
I know my cgi-app is working because I can navigate to other pages in different run modes. Please help! I see wisdom! Bob

Replies are listed 'Best First'.
Re: How to write to a file using CGI
by chromatic (Archbishop) on Jun 29, 2003 at 22:54 UTC

    There are two possibilities. First, it's possible that you might not get any data from the form field. That's unlikely as you're testing things, but it's a possibility.

    Second and likely the case, you don't have permission to open the file. You're checking the return value of open which is good. Now, check it. Look in the error log or use CGI::Carp to send the error to the browser during debugging. That'll give you a clue as to what the problem is — probably no permission to write to the current directory.

Re: How to write to a file using CGI
by Zaxo (Archbishop) on Jun 30, 2003 at 00:56 UTC

    You are overwriting each query with the next by using a fixed file name and opening '>'. CGI has a save() method which takes a filehandle and saves the form data in a format that CGI.pm can reload from.

    sub save_form { my $self = shift; my $q = $self->query(); #lexical fh, name is argument open my $fh, '>', shift || '/path/to/output.txt' or die $!; $q->save($fh); $self->run_mode('model'); }
    The use of a relative file name may be the cause of your trouble. What is the current directory when the cgi runs? Do you have permissions to write there when run by the Apache cgi_script handler?

    After Compline,
    Zaxo

Re: How to write to a file using CGI
by fglock (Vicar) on Jun 29, 2003 at 21:57 UTC

    Maybe this helps you with debugging:

    print "Writing record ... "; print FH "record is [$record]\n"; print "Wrote record: [$record]";