The Tricky.net

chmod - octal values

In php, you have to use chmod with octal values, you cannot write something like :

chmod('myFile.txt','g+w'); // this is incorrect

I propose here an easy manner to "build" this number.

Remember, there is 4 digits, which correspond to something like "0, user, group, public": 0754 for example.

Common manner

Foe each one, you define the right like that :

  • a read right correspond to 4
  • a write right correspond to 2
  • an execute right correspond to 1

You want the user to have all the rights? : 4 + 2 + 1 = 7

you want the group to have read and write rights : 4 + 2 = 6

you want that the public cannot even read the file : 0

The result is then 0760 (Don't forget the 0 at the beginning!), you write in php :

chmod('myfile.txt', 0760);

Note that the mode is a number, not a string!

If you want now things more tricky, see next part.

Advanced manner

We will now see how to define some more rights, with no limitations like the previous manner.

We have to deal with a bit of conversion between binary numbers and decimal numbers. Say you want to convert this very tricky linux formatted rights for you file: "-wxr-x--x". I show you directly this beautiful table:

User Group All
-
w x r -
x
- - x
2 1 0 2 1 0 2 1 0
0 + 21 + 20 22 + 0 + 21 0 + 0 + 20
0 3
5 1

I hope that by looking at the table you understand how this work, it's a bit complicated to explain it with words... Nevertheless here are some details :

  • the "2  1  0" are the position of the digit regarding the user, group or all users. You have then to elevate 2 to the power of the position to get a partial result.
  • 2 to the power of 2 means "2 * 2". 2 to the power of 4 means "2 * 2 * 2 * 2"
  • 20 = 1 (this is like a mathematic convention, don't ask!)

Finally we get the result 0351, corresponding to "-wxr-x--x".

Hope it was not to difficult to understand, don't hesitate to leave a comment otherwise.

Comments
Search RSS
Only registered users can write comments!

3.23 Copyright (C) 2007 Alain Georgette / Copyright (C) 2006 Frantisek Hliva. All rights reserved."