PHP CHANGE A FILE'S PERMISSIONS

A php script can be used to change a file's permissions using umask

Many Linux programs create files with permissions of 0666. So more often than not the default permissions value of 666 (i.e. rw- rw- rw- ) for a regular file will be observed. 777 (i.e. rwx rwx rwx ) for a directory. Using file permissions of 666 makes sense as it prevents files from being executed (as most files don’t need to be executed anyway). Also it’s more logical to set the executable bit on a specific file than say unset it on lots of files.

Php can be used to set the file permissions. Type the following and name the file php-file-permissions-script.php:

PHP-Script-Change-File-Permissions

I'm running the above php script as a non-root user called raspberry:

php php-file-permissions-script.php

...which yields the following two text files (with different file permissions):

PHP-Script-Change-File-Permissions

Explanation:

→This line of code creates a text file called “textfile.txt” with file permissions of rw- rw- r-- (i.e. Octal 664).
fopen('textfile.txt', 'w'); // -rw-rw-r—
→This line of code sets the mask to 0. Therefore using Octal arithmetic, 666-0 = 666
umask(000);
→As umask was used the following line of code creates a text file with permissions of rw- rw- rw- (i.e. Octal 666)
fopen('textfile2.txt', 'w');

Where:
rw- rw- r-- = 664 Octal
rw- rw- rw- = 666 Octal

• Note that scientific calculators have “Octal Mode” if you are having trouble with the octal arithmetic.
• An indepth explanation of Linux file permissions and ownership can be found here.





Linux Examples - Comments