Skip to content

Instantly share code, notes, and snippets.

@fitorec
Created October 22, 2011 02:50
Show Gist options
  • Select an option

  • Save fitorec/1305492 to your computer and use it in GitHub Desktop.

Select an option

Save fitorec/1305492 to your computer and use it in GitHub Desktop.
Chmod Recursive for PHP.
<?php
/*
* Description: chmod recursive.
* Code-Base: official documentation php.net chmod function
* Link: http://www.php.net/manual/en/function.chmod.php#105570
*
* Example usage :
* chmod_R( 'mydir', 0666, 0777);
*
*/
function chmod_R($path, $filemode, $dirmode) {
if ( !file_exists($path) ) {
print "Failed file not exists {$path}\n";
return FALSE;
}
if ( is_dir( $path ) ) {
if (!chmod($path, $dirmode)) {
$dirmode_str=decoct($dirmode);
print "Failed applying filemode {$dirmode_str} on directory {$path}\n";
print " `-> the directory {$path} will be skipped from recursive chmod\n";
return FALSE;
}
$dh = opendir($path);
while ( ($file = readdir($dh)) !== false ) {
if($file != '.' && $file != '..') { // skip self and parent pointing directories
$fullpath = $path.'/'.$file;
chmod_R($fullpath, $filemode,$dirmode);
}
}
closedir($dh);
} elseif ( is_file($path) ) {
if (!chmod($path, $filemode)) {
$filemode_str=decoct($filemode);
print "Failed applying filemode {$filemode_str} on file {$path}\n";
return FALSE;
}
} elseif ( is_link($path) ) {
print "link {$path} is skipped\n";
return FALSE;
}
}
chmod_R( 'app', 0755, 0755);
?>
<strong>finish!!!;</strong>
@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