Posted By

Tenzer on 03/10/08


Tagged

php recursive function chmod


Versions (?)

Who likes this?

5 people have marked this snippet as a favorite

sonix
jeffreality
jamesming
carlosabargues
LordBumpet


Recursive chmod in PHP


 / Published in: PHP
 

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

  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
Posted By: aslamonline on June 5, 2009

Doesn't work.

Posted By: franck_ on March 12, 2011

It works perfectly, thanks ! Simple + Clean.

Posted By: punegas on July 14, 2011

Perfect

Posted By: madc on November 6, 2011

It works, if the script is allowed to read the content of a directory. If not, it can not read and therefor change the permissions of a file/dir in it. I solved the problem by moving chmod before scandir (see http://snipplr.com/view/60573/recursive-chmod-in-php/). Also, I cleaned the snippet up a little bit.

so long. /m

You need to login to post a comment.