On Fri, 21 Nov 2003, Gohaku wrote:

> I am trying to write to a file when running the following Perl/CGI
> script:
>
>   #!/usr/bin/perl
>   print "Content-type: text/html\n\n";
>   print "Hi";
>   open(FILE,">hello.txt") || die("Cannot Open File");
>   print FILE "Hello";

The advice others have given is all valid -- you should always use
strict, warnings, and taint mode, so the opening of your script is:

   #!/usr/bin/perl -wT
   use strict;

But in any case that's been said already.

I'd also add that you should amend your `die` statement so that the output
actually indicates why it failed, by appending the `$!` error report
variable after the statement -- like this:

   open(FILE,">hello.txt") || die("Cannot Open File: $!");

That way, a more specific report is produced for you. This report will
show up in your error log in /var/log/httpd/error_log (by default). Or, as
has also been suggested, you can turn on CGI::Carp to force the error
message to appear in the browser as well as the error log.

Putting everything together, try something like this:

   #!/usr/bin/perl -wT

   use strict;
   use CGI::Carp qw[ fatalsToBrowser ];

   print "Content-type: text/html\n\n";
   print "Hi";

   open(FILE,">hello.txt") || die("Cannot Open File: $!");
   print FILE "Hello";
   close(FILE);


As has been suggested, my guess is that when you get the $! error report
turned on, you'll see a message indicating that the problem had to do with
file permissions: hello.txt needs to be writable by the account that
Apache runs under, which by default is www. The easiest way to fix this is
probably to assign ownership of that file to the Apache account:

    $ sudo chown www hello.txt
    $ sudo chmod u+w hello.txt

This changes ownership, then sets user [owner] write permissions.

Chances aren't bad that the script will work after that.



-- 
Chris Devers

Reply via email to