tulians tulians - 3 months ago 8
Perl Question

Permissions issue on opening a file - Perl, CGI

I've been trying to create a log file for an application, using Perl and CGI in an Apache server. For this reason the script needs to keep a log file, which must be opened when the script starts. From the logs I get:

Unable to open the file: Permission denied at /usr/lib/cgi-bin/generate_logs.cgi
, and the script goes as follows:

#!/usr/bin/perl
use CGI qw(:standard);
print "Content-type: text/plain\n\n";
...
open (my $logs, ">", "/path/to/directory/logs.txt") || die "Unable to open the file: $!";
...


I've been trying to use non-root paths for the
.txt
log file, like
~/Desktop
, but still the script can't create/open log the file. Don't hesitate to ask me if you need more information. Thanks in advanced.

Answer

The Apache web server typically runs as a separate user on your system. Your ~/Desktop directory will be specific to YOUR user. Any directory Apache writes to will need to be writable by the Apache user.

To find what username Apache is operating under, check your config file. This might have defaulted to /etc/httpd/conf/httpd.conf. You will probably find a line in that file with the User directive. It's probably set to user apache.

Apache already has a log directory. Usually it's /var/log/httpd. Perhaps try writing your log there.

Please note, the sample code you provided is very problematic. Each time your CGI script is run, your log file will be erased and overwritten. If it's run with concurrent users, you'll have even bigger problems. Two threads trying to write the same file, locking issues, etc. You may want to take a look at CGI::Log for something more functional.

Comments