Recursive chmod Function In PHP

10th November 2008 - 2 minutes read time

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.

  1. function chmod_R($path, $filemode) {
  2. if ( !is_dir($path) ) {
  3. return chmod($path, $filemode);
  4. }
  5. $dh = opendir($path);
  6. while ( $file = readdir($dh) ) {
  7. if ( $file != '.' && $file != '..' ) {
  8. $fullpath = $path.'/'.$file;
  9. if( !is_dir($fullpath) ) {
  10. if ( !chmod($fullpath, $filemode) ){
  11. return false;
  12. }
  13. } else {
  14. if ( !chmod_R($fullpath, $filemode) ) {
  15. return false;
  16. }
  17. }
  18. }
  19. }
  20.  
  21. closedir($dh);
  22.  
  23. if ( chmod($path, $filemode) ) {
  24. return true;
  25. } else {
  26. return false;
  27. }
  28. }

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.