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

I seem to be having an issue with CGI and writing to a file. I have the CGI cript collect input and then write the input to a file or append. I'm guessing CGI still thinks its printing to the HTML or something can any one give this code a fix?
use strict; use CGI qw(:standard); print header, print start_html("test"), hr(); if (param("name")) { my $name = param("name"); #the problem seems to be here i have tried print end_html() #that didn't work eather any ideas open (TMP, ">textfile"); print TMP $name; close (TMP); } else { print start_form(); print p("Type your name", textfield("name")); print p(submit("Submit")); } print hr(); print end_html();
Thanks for the help, I figured out the problem.

Replies are listed 'Best First'.
Re: CGI, write to file
by brian_d_foy (Abbot) on Feb 27, 2005 at 23:48 UTC

    Typically, a CGI script is run as the webserver user and has very limited permissions so it cannot write to files.

    You need to check the return value of that open(), and go from there. Check the error log for the message

    open( TMP, ">textfile" ) or print STDERR "[$0] Could not open file! $!";
    --
    brian d foy <bdfoy@cpan.org>
Re: CGI, write to file
by chas (Priest) on Feb 27, 2005 at 23:58 UTC
    print header, print start_html("test"), hr(); looks problematical to me - the comma after header, in particular, causes the Content-Type declaration to be printed in the wrong place, I think. Did you mean ; instead of , there?
    chas
Re: CGI, write to file
by Tanktalus (Canon) on Feb 28, 2005 at 02:04 UTC

    Given that you're not really saying what the problem looks like ("doesn't work" isn't a problem - it works fine, just not the way you expected it to), I'm going to hazard a guess and say that you're expecting appending to a file, and wondering why the file only ever has one name in it. Try using:

    open(TMP, ">>textfile");
    Or, if that file simply doesn't exist, try:
    open(TMP, ">>/tmp/textfile");

Re: CGI, write to file
by artist (Parson) on Feb 27, 2005 at 23:56 UTC
    If you make the file writeable by all users, before running the CGI script, you can write to that file via CGI script.
Re: CGI, write to file
by cbrandtbuffalo (Deacon) on Feb 28, 2005 at 01:20 UTC
    As a test, you could also try calling the script with the name parameter in the URL with something like http://your_server/script.pl?name=my_name

    This will help you determine if the problem is with your form or your script. You might also want to print something in the branch that writes to the file. For example, print the param back to yourself.

Re: CGI, write to file
by larryp (Deacon) on Feb 27, 2005 at 23:40 UTC

    What errors are you getting? It's hard to diagnose the problem without knowing what error codes you're seeing. Furthermore, what resources have you consulted to try to solve the problem?