PHP: fopen() Permission denied

Viewed 114150

I am confused with this code:

test.php:

fopen('test.txt','a+');

when I execute it, I get an error:

Warning: fopen(test.txt): failed to open stream:
     Permission denied in /var/www/html/yuelu3/mobile/text.php on line 2

test.txt:

-rwxrwxrwx. 1 jt jt     87 10月  7 20:58 test.txt

where is the problem?

Thanks a lot!I have found the problem,I use FC13,because of the protect of SELinux,some action is denied.So, I just need to get rid of the protect.

10 Answers

I'm using an Apache HTTP server v2.4, I think the following method will work for most people on linux:
first thing check who is the user running 'httpd'.
It is daemon in my case, and I'm not sure if it is the case for everybody. you can do so using:
ps -ef | grep 'httpd'

once you're sure that the user daemon is the owner of the process httpd, change the owner of the folder in which you want the permission to write to deamon

sudo chown daemon /path/to/folder

this will change only the user, the group of that directory remain unchanged. if you want the group also to be able to write, make sure that it has write permission

sudo chmod g+w /path/to/folder

In my case these steps helped me:

  • Verify the process user using this command ps -ef
  • Result could be:
UID        PID  PPID  C STIME TTY          TIME CMD
www-data    18     1  0 15:43 pts/0    00:00:00 apache2 -DFOREGROUND
  • Add www-data user as owner of /var/www/html/ folder
chown -R www-data:www-data /var/www/html/

Worked perfectly in a Docker running some version of PHP, but when I switched to Xampp for a quick test (since MySQL actually out of the box runs faster in Xampp) it stopped working. So this solved the task, just including the actual path to the file. This is most likely just due to different environment variables that varies in different versions and settings.

$filepath =  __DIR__ . DIRECTORY_SEPARATOR;
$in = fopen($filepath . 'test.txt','a+');

In my case the reason was: "0644" permission for the file instead of "0777" (after moving from another hosting).

Related