Skip to content

Instantly share code, notes, and snippets.

@alairock
Last active September 8, 2022 15:18
Show Gist options
  • Save alairock/5498955 to your computer and use it in GitHub Desktop.
Save alairock/5498955 to your computer and use it in GitHub Desktop.
Recursive Chmod in php
<?php
function recursiveChmod ($path, $filePerm=0644, $dirPerm=0755) {
// Check if the path exists
if (!file_exists($path)) {
return(false);
}
// See whether this is a file
if (is_file($path)) {
// Chmod the file with our given filepermissions
chmod($path, $filePerm);
// If this is a directory...
} elseif (is_dir($path)) {
// Then get an array of the contents
$foldersAndFiles = scandir($path);
// Remove "." and ".." from the list
$entries = array_slice($foldersAndFiles, 2);
// Parse every result...
foreach ($entries as $entry) {
// And call this function again recursively, with the same permissions
recursiveChmod($path."/".$entry, $filePerm, $dirPerm);
}
// When we are done with the contents of the directory, we chmod the directory itself
chmod($path, $dirPerm);
}
// Everything seemed to work out well, return true
return(true);
}
@maxpowel
Copy link

maxpowel commented Jan 4, 2014

Hi, there is a bug in this code (I have suffered it :P)
If you have a directory with a filename with a symbol like dollar ($) in the begining you will be lost in an infinite loop. The reason is that a file like this goes before "." and ".." when you do scandir. By this way, using array_slice you will remove only this file (for example $testfile.html) and not "." directory. You will get paths like "directory./././././././" until time execution limit

@alairock
Copy link
Author

alairock commented Jan 9, 2014

Awesome, thanks :

@MathiasReker
Copy link

MathiasReker commented Aug 4, 2022

Nice script. Thanks for sharing. :-)
I would like to share a library I have coded with the same goal.

Example of usage:

<?php

use MathiasReker\PhpChmod\Scanner;

require __DIR__ . '/vendor/autoload.php';

(new Scanner())
    ->setDefaultFileMode(0644)
    ->setDefaultDirectoryMode(0755)
    ->setExcludedFileModes([0400, 0444, 0640])
    ->setExcludedDirectoryModes([0750])
    ->scan([__DIR__])
    ->fix();

Full documentation: https://github.com/MathiasReker/php-chmod

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment