Last active
September 8, 2022 15:18
-
-
Save alairock/5498955 to your computer and use it in GitHub Desktop.
Recursive Chmod in php
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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); | |
} |
Awesome, thanks :
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
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