Recursive chmod in PHP


/ Published in: PHP
Save to your folder(s)

A small function I made to chmod directories and files recursively, with different permissions.


Copy this code and paste it in your HTML
  1. <?
  2. /**
  3.   Chmods files and folders with different permissions.
  4.  
  5.   This is an all-PHP alternative to using: \n
  6.   <tt>exec("find ".$path." -type f -exec chmod 644 {} \;");</tt> \n
  7.   <tt>exec("find ".$path." -type d -exec chmod 755 {} \;");</tt>
  8.  
  9.   @author Jeppe Toustrup (tenzer at tenzer dot dk)
  10.   @param $path An either relative or absolute path to a file or directory
  11.   which should be processed.
  12.   @param $filePerm The permissions any found files should get.
  13.   @param $dirPerm The permissions any found folder should get.
  14.   @return Returns TRUE if the path if found and FALSE if not.
  15.   @warning The permission levels has to be entered in octal format, which
  16.   normally means adding a zero ("0") in front of the permission level. \n
  17.   More info at: http://php.net/chmod.
  18.   */
  19.  
  20. function recursiveChmod ($path, $filePerm=0644, $dirPerm=0755) {
  21. // Check if the path exists
  22. if (!file_exists($path)) {
  23. return(false);
  24. }
  25.  
  26. // See whether this is a file
  27. if (is_file($path)) {
  28. // Chmod the file with our given filepermissions
  29. chmod($path, $filePerm);
  30.  
  31. // If this is a directory...
  32. } elseif (is_dir($path)) {
  33. // Then get an array of the contents
  34. $foldersAndFiles = scandir($path);
  35.  
  36. // Remove "." and ".." from the list
  37. $entries = array_slice($foldersAndFiles, 2);
  38.  
  39. // Parse every result...
  40. foreach ($entries as $entry) {
  41. // And call this function again recursively, with the same permissions
  42. recursiveChmod($path."/".$entry, $filePerm, $dirPerm);
  43. }
  44.  
  45. // When we are done with the contents of the directory, we chmod the directory itself
  46. chmod($path, $dirPerm);
  47. }
  48.  
  49. // Everything seemed to work out well, return true
  50. return(true);
  51. }
  52. ?>

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.