Reputation: 2209
On my server I have some files with different permissions.
In my php
script, I want to add writing permission to the group for each of these files.
Using linux cmd, chmod g+w file
does the job.
But how to do that using php chmod()
?
This is what i tried so far:
$filePermission = fileperms('myFile.txt');
# g+w = 020
chmod('myFile.txt', $filePermission+20);
This gives me what i want, but is there a php
alternative for linux chmod g+w
?
Upvotes: 1
Views: 114
Reputation: 11354
The syntax g+w
is not valid for PHP, nor most programming languages as the underlying operating system has no concept of these values. The chmod
syscall only accepts octal values, not strings. On your system the chmod
command line executable has implemented a parser to implement this custom feature.
While your example "works", it will cause undesirable results if the file already has g+w, as adding another 20 will turn on additional bits and grant the file extra permissions you did not intend. For example, if the file permission was 020
and you added 020
to it, it would become 040
.
Posix file permissions are octal bits where each digit represents a combination of read, write and execute. As such the add operation (+
) is incorrect, you instead need to use bitwise operations such as AND
and OR
to turn individual bits on or off. For PHP, C, C++ and most common languages the AND operator is the ampersand symbol (&
) and the OR operator is the pipe symbol (|
). Since we wish to turn bits on, we need to use the OR operator.
The correct way to handle this would be:
$filePermission = fileperms('myFile.txt');
chmod('myFile.txt', $filePermission | 020);
Note that I have prefixed the number with a 0
, this will make PHP interpret the number as octal rather then decimal.
Recently I made a video on this to try to help people understand chmod
and how the octal notation works, it may help you with what you are attempting to accomplish. https://www.youtube.com/watch?v=j8FLsxdl0ns
If you wish to have the friendly menomic support as the command line binary has, you will need to implement the parser yourself, or invoke the command line binary from PHP, for example:
exec('/bin/chmod ' . escapeshellarg($perms) . ' ' . escapeshellarg($file));
Note however that this usage is far slower then using the inbuilt chmod
function in PHP directly. It could also open you up to potential security issues.
Upvotes: 3