PHP solve fopen() Permission denied error

When trying to open a file using fopen(), you might see an error saying permission denied as follows:

Warning: fopen(log.txt): failed to open stream:
  Permission denied in /var/www/html/app.php on line 2

This error frequently occurs on a Linux system because of two things:

  1. The protection of SELinux
  2. The owner of the folder of the file you try to open is root

To resolve this issue, you can try to disable SELinux first.

Disabling SELinux to fix fopen() issue

To disable SELinux, run the following command from your terminal:

setenforce 0

The setenforce command will disable SELinux until you reboot the system.

If you still get the permission denied error with fopen(), try to change the owner of the file and directory that you want to access.

Change directory owner to solve fopen() issue

Most often, the fopen() function tries to access a file using the web server user.

This means PHP will use apache user when you have Apache server, or nginx when you have Nginx server.

When the root is the owner of the file you tried to access, it will cause the permission denied error.

Check the owner of your file by running ls -l command from the terminal:

$ ls -l log.txt
-rwxrwxrwx  4 root root 4096 Sep 15  2021 log.txt

To enable access with fopen(), you need to change the owner of the file you want to access.

Run the chown command to change the file owner as follows:

chown apache:apache log.txt
# or
chown nginx:nginx log.txt

Sometimes, you also need to change the owner of the directory where the file is located.

This is because access to some directories are restricted only to the owner.

In my case, the full URL of the file is /var/log/httpd/ so I change the directory httpd owner as follows:

chown apache:apache /var/log/httpd

Keep in mind that changing owners and permissions in your system may introduce security issues.

When possible, it’s better to move the files and directories that you need access to another location.

Create a new directory that can be accessed by PHP fopen() and put all files you need in that directory.

And that’s how you solve the PHP fopen() permission denied error. I hope this tutorial has been useful for you 🙏

Take your skills to the next level ⚡️

I'm sending out an occasional email with the latest tutorials on programming, web development, and statistics. Drop your email in the box below and I'll send new stuff straight into your inbox!

No spam. Unsubscribe anytime.