I spend quite a lot of time on StackOverflow, both in terms of finding answers for something I need, and also for helping people out with their issues. One question I see quite a lot is around security permissions for creating files on the server. Usually these questions are for PHP, and as such I’m going to address this post as if PHP developers are sensible and deploy on a LAMP stack.
More often than not, I see the posts and they have something along the lines of the following:
I’ve set the permissions to 777 but it’s still not working
It makes me want to turn into the Hulk and smash things.
There is no real reason that any file or directory within your website needs to have read, write and execute permissions. In fact, quite the opposite. There is no reason I can think of they should ever have that level of permission. Setting it to that means you either know something I don’t (quite possible) or you’re an idiot who shouldn’t be allowed near a file system (more likely).
The issues of not being able to write a file via a web page are going to come as a result of the web server not having permission to write to a file or directory (yes, I know directories are just a special kind of file, but I’ll skip that one for now). This is most likely because the files are either owned by root, or by your user directly. There is usually a simple fix. Open up your terminal, navigate to the folder which contains your website folder and type the following:
sudo chown -R www-data:www-data website
Then, when/if prompted, type the password to allow the sudo part to work.
The net result is that the folder is now owned by the user Apache runs under (it’s www-data by default) and also to the www-data group. No need to give my dog access to your files on your server, just let Apache do what it needs with them. Here’s a bigger breakdown of the command:
- Tell the terminal you want this running with su permissions, because normally you wouldn’t be allowed to do this (if the files are assigned to root)
- Change the owner of the file/directory
- For the folder we are going to specify, and everything within it, recursively
- To the www-data user and the www-data group
- The folder which contains the website files you are wanting to change the owner for
That has fixed the issue of not being able to write a file for me in 99% of cases I’ve had issues (1% was disk full – poor admin on my part).
If at this point you are wondering why you need sudo when you can just log in as root, read through this article on linuxacademy. Once you’ve done that, seriously consider if you need to allow root to login, and then look through thinkgeek’s article on disabling root.