By default, most files and directories are not writable by the web server. This is an important security precaution, as this prevents minor (and, sadly, common) security flaws in tools like PHP from turning into catastrophic site-wide destruction.
Consequently, the first step is to determine whether you should make a given file or directory writeable by the web server (e.g. from PHP or a CGI script). Here is our official recommendation on that subject:
No file should ever be both modifiable over the web and executable over the web.
For example, no PHP file or CGI script should ever be web-writeable. Writeable content should be minimized and limited to static items like graphics.
Once you have determined that it's appropriate to make something writeable, the specific requirements differ depending on whether you are modifying an existing file or creating a new one:
- To create and write to a new file, the parent directory must be writable by the web server.
- To write to an existing file, that file must be writable by the web server.
(Files created by the web server will generally be writeable by the web server by default.)
The web server runs as the "web" user and is in (only) the "web" group. Each site also has its own private user and group unique to that site. When you create a file, it will go into the site's private user and group. As a result, there are three ways to mark a file or directory as writeable by the web server.
- You can leave the user and group ownership as-is and grant the "other" user (i.e. the web server) write permissions with a command like: chmod o+w example.txt
- You can set the group ownership to "web" with a command like chgrp web example.txt and then grant that group write permissions with a command like chmod g+w example.txt
- If the web server creates the file or directory, it will be owned by the "web" user and will usually have "user" write permissions by default. (The equivalent of chmod u+w example.txt.)
So, setting files or directories to be writable by the web server is a two step process:
- Check the user and group ownership of the file and/or parent directory (usually shown by SFTP/FTP clients or the ls -l shell command) to determine whether the web server will be treated as user, group, or other when accessing it.
- Make sure that the appropriate user, group, or other write permission is set via chmod on the command line or the equivalent function in your SFTP/FTP tool.
Usually people have trouble getting the web server to write files, but the reverse problem is also possible: when the web server creates files, it is possible for it to set them such that you can't access (or delete) them. If this happens, you can repossess the offending files. To prevent it from happening in the first place, make sure your scripts use an appropriate umask, such as 002. This will cause files and directories to be created with read and write permissions for the web group, which you are in, so you will retain access to them.