PHP-tip: How to fix problems with file permissions

Have you tried to create or read a file with fopen, file_get_content or file_put_content and only getting permission denied.
A reason for this error message can be that the file you are about to read/write already exists and with your account as owner.
A quick, and safe, fix is to change the owner and group of the file to the same owner/group as the apache-server is running as.
Example:
Let’s say you are about to update index.htm. This file was uploaded by you to the ftp-server, and so the file is owned by foo (you) which is a member of the group bar. The Apache-server how ever is being run by user:group apache. the user:group apache does not have permission to change anything to this file.
So what you do is:

  • Connect to the web server with ssh (shell account)
  • Change ownership to the file to apache by running chmod apache:apache index.htm

Now you should be able to change the content of the file with PHP.
I have seen suggestions on websites where they say that you should change the mode to 775 or even worse, 777. This is a security breach and so you should not do so.
Hope this helps someone out

Suggested links

You can leave a response, or trackback from your own site.

Leave a Reply