0

I'm running a server on CentOS 7. User apache | Group apache has 775 permissions on /var/www/html When I execute a PHP file that wants to create a new file in root dir (/var/www/html/) I get the following error Warning: file_put_contents(file.bin): failed to open stream: Permission denied in /var/www/html/file.php

PHP code:

<?php
ini_set('display_errors', 'on');
$file = 'file.bin';
$content = "Content";
file_put_contents($file, $content);
?>

I will update the question with more data but since I'm new I don't know too many things about debugging server errors.

What I tried:

  • For executing scripts (php..) I saw the user to be apache so I gave 'apache' ownership on /var/www/html/

  • tried 777 on ./html (and reversed action after it didn't work to 755)

  • Also tried cd /var/www/html chmod -R 775 . (from comments)

Tim
  • 190
  • 5
  • 19
  • 1
    You need to write to a directory that the user running the webserver has write permission to. – Barmar Mar 01 '22 at 20:57
  • `cd /var/www/html` `chmod -R 775 .` – medilies Mar 01 '22 at 21:06
  • @medilies I tried that already and setting the owner of HTML as apache (user which executes PHP files (checked that by executing a command in PHP forgot what it was) – Tim Mar 01 '22 at 23:06
  • @Barmar the thing is I can set 777 everywhere but it still can't do it – Tim Mar 01 '22 at 23:09
  • 1
    Show a [mcve], it might be something related to your code? – Nic3500 Mar 02 '22 at 03:07
  • Wait, what is the exact code? Did you `file_put_contents(/var/www/html/file.php)` ? Remember that from PHP's perspective, `/` is already under `/var/www/html`. So it should be `file_put_contents(/file.php)`. Note, not real code, just to show you that you should not use absolute patch from the system's `/`. – Nic3500 Mar 02 '22 at 03:13
  • @Nic3500 I added my code to the question. I tried `file_put_contents("/var/www/html/file.bin", "smth");` and relative path `file_put_contents("file.bin", "smth")` both produced the same error. – Tim Mar 02 '22 at 08:16

1 Answers1

1

With a high degree of probability, the issue is with selinux. if you turning off selinux with the command (from root) :

setenforce 0

and everything will work, you need to turning on selinux with the command (from root):

setenforce 1

and run the command:

chcon -R -t httpd_sys_rw_content_t /your/path

Everything must work. If this method does not help, I advise you to read answers in this question. There is an answer with a more flexible selinux settings (with using sudo semanage fcontext).

Ivan Ivanov
  • 515
  • 1
  • 5
  • 20