-1

It seems

chmod("*.txt", 0660);

doesn't work.

I know I can:

  1. chmod the files one by one: it works but I do not know all the names in advance, so I cannot use it.
  2. Use exec. It works but I don't like it for several reasons (speed, security, and so on).
  3. Use scandir. It works but again, slow and I guess too much for a simple operation

I really want to use chmod directly. Is it even possible? Thank you.

ZioBit
  • 905
  • 10
  • 29
  • 1
    Could you give more context to why you want to change permissions on files? You could do this at the point you write the files to the filesystem – Chris Townsend Jan 28 '21 at 10:59
  • That's a wonderful idea, at first I though it could be hard but... Is there a way to CREATE a file already with those attributes, or should I chmod them later? – ZioBit Jan 28 '21 at 13:41
  • And really, I would like to know WHY it has been downvoted and by whom. It's a totally legit question, I DEMONSTRATED I KNOW HOW TO DO IT in THREE DIFFERENT WAYS. Forgive me if I ask how I can do it in a fourth way. I was under the impression SO was to ask questions of which you didn't know the answer to. I guess somebody should really come to live with me in Pattaya. – ZioBit Jan 28 '21 at 13:46
  • 1
    Added an answer that I think will help. So I believe someone has marked the question down as the first sentence is chmod... doesn't work. But without any context, it does really help. Maybe say what you are trying to do. e.g. "I'm trying to iterate all of the files in a particular folder and change the permissions. I tried `chmod("*.txt", 0660);` but it didn't work – Chris Townsend Jan 28 '21 at 14:10

1 Answers1

0

So you can do this using scandir like you mentioned and yes filesystem can be pretty slow, you can add a check in so you do not do it to files you have already processed

<?php

$files = scandir('./');
foreach ($files as $file) {
    // check here so you don't have to do every file again
    if (substr(sprintf('%o', fileperms($file)), -4) === "0660") {
        echo "skipping " . $file; 
        continue;
    }

    $extension = pathinfo($file)['extension'];
    if ($extension === 'txt') {
        chmod($file, 0660);
    }
}

Or you could use glob

<?php

$files = glob('./*.{txt}', GLOB_BRACE);
foreach($files as $file) {
    // check here so you don't have to do every file again
    if (substr(sprintf('%o', fileperms($file)), -4) === "0660") {
        echo "skipping " . $file; 
        continue;
    }

    $extension = pathinfo($file)['extension'];
    if ($extension === 'txt') {
        chmod($file, 0660);
    }
}
Chris Townsend
  • 2,586
  • 2
  • 21
  • 41