We Recommend

Wicked Cool PHP: Real-World Scripts That Solve Difficult Problems Wicked Cool PHP: Real-World Scripts That Solve Difficult Problems
Wicked Cool PHP contains a wide variety of scripts to process credit cards, check the validity of email addresses, template HTML, and serve dynamic images and text.


Posted By

Tenzer on 03/10/08


Tagged

php recursive function chmod


Versions (?)


Who likes this?

4 people have marked this snippet as a favorite

sonix
jeffreality
jamesming
carlosabargues


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. {
  22. // Check if the path exists
  23. if(!file_exists($path))
  24. {
  25. return(FALSE);
  26. }
  27. // See whether this is a file
  28. if(is_file($path))
  29. {
  30. // Chmod the file with our given filepermissions
  31. chmod($path, $filePerm);
  32. // If this is a directory...
  33. } elseif(is_dir($path)) {
  34. // Then get an array of the contents
  35. $foldersAndFiles = scandir($path);
  36. // Remove "." and ".." from the list
  37. $entries = array_slice($foldersAndFiles, 2);
  38. // Parse every result...
  39. foreach($entries as $entry)
  40. {
  41. // And call this function again recursively, with the same permissions
  42. recursiveChmod($path."/".$entry, $filePerm, $dirPerm);
  43. }
  44. // When we are done with the contents of the directory, we chmod the directory itself
  45. chmod($path, $dirPerm);
  46. }
  47. // Everything seemed to work out well, return TRUE
  48. return(TRUE);
  49. }
  50. ?>

Report this snippet 

You need to login to post a comment.