Search code examples
phpfile-permissionschmod

Do I need to set "group" permissions when using chmod?


I need to set chmod for a file so that everybody can view the file, and only the web server holding it (or PHP script) can overwrite it.

What would be the correct chmod setting for this? Can you explain what groups are? Are they relevant for me?


Solution

  • Generally the file should be owned by, or be in the group of, the web server user. Assuming your web server runs under www-data, that would mean running this:

    chmod u+w file.txt        # write access for the file's user
    chmod ugo+r file.txt      # read access for user, group, other
    chown www-data file.txt   # change owner
    

    Or this:

    chmod g+w file.txt        # write access for the file's group
    chmod ugo+r file.txt      # read access for owner, group, other
    chgrp www-data file.txt   # change group
    

    The latter is useful if you wish to make the files writeable by an owner user - this is common if you wish to rsync the files, or perhaps git pull, under your normal account.

    Note that users and groups are different things. The above examples take advantage of the fact that 'www-data' is a common user that is created by installing Apache, and 'www-data' is a common group that is also created at the same time. Yes, they are named identically, and are two different things!

    You asked what a group is. It is normally used as a category for users, so for example a university might have groups called 'students' and 'staff'. Users can be added to any number of groups, so research students could arguably be added to both, for example, since they qualify as being in both categories. Membership of groups then allow system administrators to confer read and write privileges on a global basis, without having to worry about resetting users individually.

    It's worth being careful with what you make writeable by the web server, especially files and folders that are within the normal document root. If there is a vulnerability in your web app, you don't want users being able to create PHP files via the web server, otherwise arbitrary remote execution may become possible.

    To defend against this, if you are (for example) just uploading text files, do so outside of your document root, so they cannot be remotely executed. And if you are uploading images (which need to be in the doc root) disable the PHP engine for that directory.