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

Hello to all Monks,

I have created a webpage using CGI (say page.pl) and writing logs in a log file (say file.log) that already exists. Both the perl program and logfile are under same directory (say dir1) owned by application user (say app1). The directory dir1 has 755 permission.

Now I am trying to modify my code so that if the file.log doesn't exist, it should be created and should have file permission to be writable by apache (as apache is configured to run the webpage).

Can you please suggest me a clean way to do this? I have tried something like:

my $logfile = "file.log"; unless(-e $logfile) {#Create the log file if it doesn't exist open my $fc, ">", $logfile or die "Could not create file '$logfile +' $!"; close $fc; } open(my $fh, ">>", $logfile) or die "Could not open file '$logfile' $! +";

But this won't work unless the dir1 has 777 permission as it's owned by app1 and not apache. I won't be making dir1 777 at all! I found another post (#585219) which shows I can use sysopen but even with this option, the file.log will be owned by root (neither apache nor app1) and I think this means the file.log will need to have 777 permission.

I am trying to find a way to create this file.log (if it doesn't exist) in such a way that I don't have to change access to file.log or dir1 to 777. At max I can make it 775

Thank you for taking time to read this!

UPDATE: Changed subject line to mark this solved.

  • Comment on [Solved]: How to create a log file under a directory owned by app user from cgi script?
  • Download Code

Replies are listed 'Best First'.
Re: How to create a log file under a directory owned by app user from cgi script?
by stevieb (Canon) on Apr 14, 2016 at 19:11 UTC

    Why not create a new group, put both the apache user and the app user into it, then change the group ownership on the directory to the new group?

Re: How to create a log file under a directory owned by app user from cgi script?
by thomas895 (Deacon) on Apr 15, 2016 at 04:35 UTC

    Apache lets you run CGI scripts as a different user and/or group, using suexec.

    -Thomas
    "Excuse me for butting in, but I'm interrupt-driven..."
Re: How to create a log file under a directory owned by app user from cgi script?
by Perl300 (Friar) on Apr 19, 2016 at 16:59 UTC
    Thank you stevieb and thomas895. I read through some articles as directed by thomas895 about suexec but it seems a little complex for me to understand and time consuming to get done. And they have clearly mentioned that don't do it if you don't know what you are doing.

    So I'll take the suggestion from stevieb to create a new group and add both apache and application user to that group. Then will give this group write permission on the dir1 directory.