Skip to content

Instantly share code, notes, and snippets.

@jasperf
Created June 11, 2013 10:05
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save jasperf/5755794 to your computer and use it in GitHub Desktop.
Save jasperf/5755794 to your computer and use it in GitHub Desktop.
PHP Script to change file and folder permissions See http://www.webhostingtalk.com/showthread.php?t=218863 #PHP #permissions #chmod
<?php
//http://www.webhostingtalk.com/showthread.php?t=218863
$start_dir = 'whatever'; // Starting directory no trailing slashes.
$perms['file'] = 0644; // chmod value for files don't enclose value in quotes.
$perms['folder'] = 0755; // chmod value for folders don't enclose value in quotes.
function chmod_file_folder($dir) {
global $perms;
$dh=@opendir($dir);
if ($dh) {
while (false!==($file = readdir($dh))) {
if($file!="." && $file!="..") {
$fullpath = $dir .'/'. $file;
if(!is_dir($fullpath)) {
if(chmod($fullpath, $perms['file'])) {
echo "\n<br><span style=\"font-weight:bold;\">File</span> ". $fullpath .' permissions changed to '. decoct($perms['file']);
}else {
echo "\n<br><span style=\"font-weight:bold; color:#ff0000;\">Failed</span> to set file permissions on ". $fullpath;
}
}else {
if(chmod($fullpath, $perms['folder'])) {
echo "\n<br><span style=\"font-weight:bold;\">Directory</span> ". $fullpath .' permissions changed to '. decoct($perms['folder']);
chmod_file_folder($fullpath);
}else {
echo "\n<br><span style=\"font-weight:bold; color:#ff0000;\">Failed</span> to set directory permissions on ". $fullpath;
}
}
}
}
closedir($dh);
}
}
chmod_file_folder($start_dir);
?>
@MathiasReker
Copy link

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

@jasperf
Copy link
Author

jasperf commented Sep 9, 2022

Thanks for sharing and glad you liked the script @MathiasReker !

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