Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php permissions to create a file

I'm running an apache server on lubuntu, and am trying to use php to write a text file that the users can then download. I changed the permissions as so:

sudo chmod 775 /var/www -R

But I still get an error when I execute the script:

Warning: fopen(3): failed to open stream: Permission denied in /var/www/myPage.php on line 217 Could not open file!

Here is the php code:

    $filename = $liste[0][0];

    $fh = fopen($filename, "x+") or die("Could not open file!");

    fwrite($fh, "foo") or die("Could not write to file");

    fclose($fh);

Do I need to change other permissions? Or is there another way to do what I'm trying to do? Thanks

like image 620
Jessica Chambers Avatar asked Jan 07 '23 05:01

Jessica Chambers


1 Answers

Writing into a folder requires the Apache user to have writing, reading and executing privileges on that folder.

  1. So, first try to identify the name of the Apache user (often www-data).

  2. Then check if that user is either the owner or in the group of the folder where you want to write files.

  3. Give write, read and execute (7) privileges on that folder for that user. Give everyone else who don't need writing the read and execute privileges (5) on the same folder.

  4. (recommended) Give write and read (6) privileges to your files for the www-data user. Everyone else only need read privileges (4).

If www-data is neither the owner nor in the group of the file, then you should change either one of them. After doing this, you may find yourself unable to access the web folder if you access the server with a user other than www-data and other than root (like "webeditor"), and that user is neither the owner nor in the group.

I recommend:

  1. Set the owner and group to the Apache user/group.

    chown -R www-data:www-data /var/www
    
  2. Add the webeditor user (or whichever you use to connect to the server on ssh or ftp) to the www-data group.

    usermod -a -G www-data webeditor
    
  3. Give folders the write, read and execute privileges to the owner. Avoid the writing privileges on everyone else.

    find /var/www -type d -exec chmod 755 {} \;
    
  4. Files do not require the execution privilege. Only reading and writing is necessary for the www-data user, the rest only need reading privileges, so 644 is enough for our files.

    find /var/www -type f -exec chmod 644 {} \;
    
like image 132
Marc Compte Avatar answered Jan 08 '23 19:01

Marc Compte