Recursive chmod Function In PHP

File permissions are important, especially if you want to let a user agent view a file. If the file doesn't have the correct permissions then it will not be accessed and could cause your script to fail. To get around this you might want to use the following function. It uses the PHP function chmod(), which sets permissions, but it does this recursively from wherever you set it off from.

function chmod_R($path, $filemode) {
 if ( !is_dir($path) ) {
  return chmod($path, $filemode);
 }
 $dh = opendir($path);
 while ( $file = readdir($dh) ) {
  if ( $file != '.' && $file != '..' ) {
   $fullpath = $path.'/'.$file;
   if( !is_dir($fullpath) ) {
    if ( !chmod($fullpath, $filemode) ){
     return false;
    }
   } else {
    if ( !chmod_R($fullpath, $filemode) ) {
     return false;
    }
   }
  }
 }
 
 closedir($dh);
 
 if ( chmod($path, $filemode) ) {
  return true;
 } else {
  return false;
 }
}

This is especially useful for some scripts that create or copy files as these files might be created without the correct permissions. You can call this function by giving it a directory and an octal value for the preferences. Note that the octal value is important. If you want to give the files the permission of 775 then you must use 0775. The following is an example of this function in action, it had been given the current directory that the script resides in to run from.

chmod_R(dirname(__FILE__),0775);

Everything under this directory, including the script file, will be set to 0775, which is standard for most purposes.

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
5 + 9 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.