PHP DevCenter

oreilly.comSafari Books Online.Conferences.

We've expanded our Linux news coverage and improved our search! Search for all things LAMP across O'Reilly!

Search
Search Tips

advertisement

Listen Print Discuss Subscribe to PHP Subscribe to Newsletters

PHP Foundations Working with Permissions in PHP, Part 1

by John Coggeshall
02/06/2003

In the past few columns, I have been discussing using PHP's file I/O capabilities for manipulating both files and directories. This week, we'll take a slight detour from a strictly PHP-related subject and discuss file permissions in Unix systems. If you are using PHP in a Windows environment (or other environment without a permission system), this column may not apply to you.

How Permissions Work

Before we can explain how permissions can be used from within PHP applications, you'll need a little background on how permissions work in general. Although today's column only discusses Unix permission-related commands, these commands directly relate to their PHP counterparts discussed in my next column. If you haven't ever really worked with the permissions system in PHP (or need a refresher) read on.

In a Unix environment, all files and directories are owned by two different entities -- a user and a group. (A group represents multiple individual users.) Likewise, each file in the file system has three different permission sets which determine who can access a particular file or directory. Specifically, every file in a Unix system has the following permission sets: user-level, group-level, and global-level.

For each permission set, three different flags exist: read, write, and execute. If a particular user does not have the read flag set, he will be unable to read the desired file (or the files in a directory). Likewise, if a user does not have the execute permission on a file, she will be unable to execute that program. When a user creates a file, that file automatically is owned by the user and group to which the user belongs. In order to change the owner of a particular file the chown Unix command is used as follows:

[user@localhost]$ chown theuser thefilemask

Also in PHP Foundations:

Using MySQL from PHP, Part 2

Using MySQL from PHP

MySQL Crash Course, Part 3

MySQL Crash Course, Part 2

MySQL Crash Course

where theuser represents the username to change the file mask specified by thefilemask. Please note that this command can only be executed by a user who has super-user privileges (such as root).

Changing the group to which a file belongs to is done via the chgrp Unix command. Unlike chown, which requires super-user privileges, chgrp can be used by any user. The one restriction that applies is that chgrp will only allow the user to change the group of a file as long as the user belongs to that group. For example, a given user who belongs to the groups foo and bar can change the group of a given file to either foo or bar but not foobar -- because he does not belong to that group.

As I mentioned, for a given file there are three different permission levels that apply to each file and directory: the user-level, group-level, and global-level. Each level is independent of the other, and is used to permit read, write, or execution access for the given file. From a Unix console, one can see the owner, group, and permissions assigned to these three groups by executing the ls (list) command in a given directory and specifying the -l (long) tag as shown:

[user@localhost]$ ls -l
rwx-w-r--    4 php      mygroup          4096 Nov  7 15:52 mydirectory

In the above example, the directory mydirectory is owned by the user php and belongs to the group mygroup. The string drwx-w-r-- identifies the permissions.

If the permission has been granted (read, write, or execute) then that letter will be displayed for the particular group. Otherwise, a dash is shown. Thus, in the example above, this particular file has been given read, write, and execute permissions for the owner of the file (the user php). However, those who belong to the group mygroup can write to this file, while the remainder of people (global) can only read the file. The one flag that hasn't been identified yet (the first character, d) identifies this particular file as a directory.

Although permissions are fairly simple for normal files, they take on a slightly different meaning when applied to directories. Specifically, read permission is required in order for a user to view the contents of the directory. Write permission allows a user to create or remove files within the directory. Execute permission is required in order to access the directory at all. Note that a user with write permission to a directory will be able to delete any file in that directory, even if she lacks write permission for that file.

So how does one modify the permissions of a file? Unix permissions are handled through a command called chmod:

[user@localhost]$ chmod 755 thefilemask

In the above example, 755 is the numeric representation of the permissions to set, and thefilemask is the file mask of the affected files. Note that only the owner or a group member may modify the permissions of a file. There are two different ways to assign or to revoke permissions for a file -- one text-based and the other numeric-based. Because PHP does not provide means to modify permission values using the text-based method I will only discuss the numeric method.

The permissions of all of the permission groups can be represented by different numeric values. Added together, this represents the complete numeric permission value. The values of the different permission levels are:

Related Reading

Learning the Unix Operating System
A Concise Guide for the New User
By Jerry Peek, Grace Todino-Gonguet, John Strang

ValuePermission Level
400Owner Read
200Owner Write
100Owner Execute
40Group Read
20Group Write
10Group Execute
4Global Read
2Global Write
1Global Execute

In order to give read and execute permission to the file's owner, write permission to the group, and read permission to everyone else (global) the permission value would be:

  400Owner Read
+ 100Owner Execute
+  20Group Write
+   4Global Read
= 524Total Permission Value

Applying these permissions to the file is as simple as using the chmod command:

[user@localhost]$ ls -l
-rwx-w-r--    4 php      mygroup          4096 Nov  7 18:52 myfile
[user@localhost]$ chmod 524 myfile
[user@localhost]$ ls -l
-r-x-w-r--    4 php      mygroup          4096 Nov  7 18:60 myfile
[user@localhost]$

PHP Returns Next Time!

That's it for today's column. Although no PHP commands were actually discussed, having a reasonable understanding of the Unix permission system (especially when working with files) is critical to PHP applications. Without being familiar with this subject it is very easy to open up your scripts to malicious users. In my next column, I'll take the Unix commands discussed today and apply them to the counterpart PHP functions.

John Coggeshall is a a PHP consultant and author who started losing sleep over PHP around five years ago.


Read more PHP Foundations columns.

Return to the PHP DevCenter.


Have a question about Unix file permissions? Ask it here!
You must be logged in to the O'Reilly Network to post a talkback.
Post Comment
Full Threads Oldest First

Showing messages 1 through 9 of 9.

  • CHMOD
    2007-05-07 10:00:17  samxz [Reply | View]

    This is a good article about CHMOD

    http://www.totalchoicehosting.com/forums/index.php?showtopic=28009

    Setting CHMOD is a no no!
    Setting 766 for the files you want to write opens you up to hackers that are on your shared host account!


    I recommend to use SQL to store data, you need a user id and password to have access to it.
    Very secure and easy to use!

    http://www.travelconnecxion.com
    • CHMOD
      2007-07-08 07:54:30  samxz [Reply | View]

      After recent work with phpBB I found out there are many exploits for hackers with embeding PHP in gif or jpg files.

      So CHMOD to 766 will not protect you fully.

      Best way is to use htaccess pasword protected directories for storing user uploaded files.
      Depending on a server configuration one can change mod to 777 on htaccess password protected dir, but other times you cannot and can only write to a file if a file exists.
      (So unless you are 777 you cannot write to a new file.)
      To get around writing to a new file problem store the uploaded files in a sub directory of root not in public_html
      Then you will be fully protected, because one cannot access that directory from www

      Another nice trick, is to change mod in PHP when you write to a file to public and change the mod back to global after finished writting.

      This is also handy, write to a temp file then flush it with heloo!

      Okay Foo to you all.
  • Global-level Permissions
    2006-10-12 03:18:41  Urlene [Reply | View]

    Good Day, which command do I use to give global-level permissions on a /etc file?
  • I, too, was a little disappointed by this article
    2005-02-24 11:16:50  RichardBronosky [Reply | View]

    It's actually a great article on Unix file permissions. Something that I was really confused about when I started using Unix several years ago. But I was able to find an article very similar to this back then and I now don't have to think twice about chmod'ing files and such.

    But, the point is that there are tons of very similar articles out there.
    http://www.google.com/search?q=unix+file+permissions+tutorial
    The google search above returns 305,000 of them.

    I think that the author should have just wrote his "Working with Permissions in PHP, Part 2" and used one of the existing tutorials as a prerequisite.

    What I'd really like to see is an intelligent disscussion on the problem of using permissions that would allow a PHP based CMS to write to files as the www user and allow you to write to the files as your ftp/shell user. The common approach is to use chmod 666 (global read+write). But that is a big security risk on a shared environment.

    Keep in mind that this is on an environment where I do not have root access or access to /bin/su. This is the case for most PHP hobbyists. Which includes my personal projects like http://bronosky.com that is hosts using a cheap shared plan. At work I have root access, or can request changes from the admins in other divisions.

    On boxes I administer I just make myself a member of the www group which Apache normally belongs to. Any files I want PHP to write to are "chgrp www"'ed and "chmod g+w"'ed. This helps but is not perfect. Most importantly, you will not get access to the www group on a share host.

    Is there a way to get php to exec() as my user?
  • Not found anywhere else
    2003-12-13 07:44:00  anonymous2 [Reply | View]

    I'm glad I refound this site. Now I can finally understand some of the troublesome basic security stuff I'm currently dealing with.

    Thanks very very much,

    Marc Schillemans
  • One of the biggest pitfalls on X-nix servers!
    2003-04-16 10:42:33  anonymous2 [Reply | View]

    Nice explanation. This is essential!
  • PHP? Or unix?
    2003-02-23 18:08:41  anonymous2 [Reply | View]

    What did this have to do with PHP? This is basic unix permissions, I expected this article to discuss things like problems with ownership in php safe mode that you run into when creating directories with php, this article really had nothing to do with PHP. Although I reallize that it's only part one, this whole part could have been skipped over by a link to this same information under a properly titled article "Basic unix permissions".
    • PHP? Or unix?
      2003-04-16 10:47:40  John Coggeshall | O'Reilly Author [Reply | View]

      Understanding the fundamentals of UNIX permissions is absolutely essential for any explaination of how they pertain to PHP. As you've already observed this is only part one :) Expect to see a PHP-focused approach in the very near future.
  • PHP Developer Community
    2003-02-10 22:45:54  plaw [Reply | View]

    That this kind of basic information needs to be provided to the PHP developer community helps explain the overwheming preponderance of security vulnerabilities in PHP and applications developed using it.
    This is a shame as much of the PHP software has a much more polished look than other web-based software available. And, as a whole, the PHP software is more feature rich.


Recommended for You

  1. Cover of Learning PHP, MySQL, and JavaScript
    Learning PHP, MySQL, and JavaScript
    Print: $39.99
    Ebook: $31.99
  2. Cover of Mastering Regular Expressions
    Mastering Regular Expressions
    Print: $44.99
    Ebook: $35.99
  3. Cover of PHP Anthology
    PHP Anthology
    Print: $39.95
  4. Cover of Building Tag Clouds in Perl and PHP
    Building Tag Clouds in Perl and PHP
    Ebook: $9.99

Tagged Articles

Post to del.icio.us

This article has been tagged:

php

Articles that share the tag php:

Understanding MVC in PHP (477 tags)

The PHP Scalability Myth (123 tags)

The Dynamic Duo of PEAR::DB and Smarty (53 tags)

PHP Form Handling (43 tags)

Very Dynamic Web Interfaces (39 tags)

View All

Sponsored Resources

  • Inside Lightroom
Advertisement

Sponsored by:

O'Reilly Media

©2010, O'Reilly Media, Inc.
(707) 827-7000 / (800) 998-9938
All trademarks and registered trademarks appearing on oreilly.com are the property of their respective owners.
About O'Reilly
Academic Solutions
Authors
Contacts
Customer Service
Jobs
Newsletters
O'Reilly Labs
Press Room
Privacy Policy
RSS Feeds
Terms of Service
User Groups
Writing for O'Reilly
Content Archive
Business Technology
Computer Technology
Google
Microsoft
Mobile
Network
Operating System
Digital Photography
Programming
Software
Web
Web Design
More O'Reilly Sites
O'Reilly Radar
Ignite
Tools of Change for Publishing
Digital Media
Inside iPhone
makezine.com
craftzine.com
hackszine.com
perl.com
xml.com

Partner Sites
InsideRIA
java.net
O'Reilly Insights on Forbes.com