Using PHP to change file and directory permissions in a web server

Here is a PHP script to recursively change file and directory permissions in your web server. This is useful for Drupal users who have their sites hosted in web hosts that don't allow them to easily do a recursive chmod. This version is based on the one posted at and is geared towards Drupal users.

This version will change the file and directory permissions to chmod 0555. If you need to change the permissions to something else, like chmod 0755, to work on the files just replace 0555 with 0755 in the script. It will skip the files at the root folder and it will also skip the "sites" directory and its files and sub directories. This is so that you can set those files to have different permissions or not mess up the current permissions they have (some people have "private" directories inside their "sites" directory).

To use the script, place it in your root Drupal folder, where the Drupal files are. Then in your browser visit, where yoursite is the name of your website and thisscript is the name you gave this script. Delete the script from the server when you are done.

   // code based on
   // this version skips the sites folder
   // pass current directory

   function file_fix_directory($dir, $nomask = array('.', '..')) {
      if (is_dir($dir)) {
         if ($dir != dirname(__FILE__)){
            // Try to make each directory 0555 except the root dir and its files
            if (@chmod($dir, 0555)) {
               echo "<p>Made 0555: " . $dir . "</p>";

      if (is_dir($dir) && $handle = opendir($dir)) {
         while (false !== ($file = readdir($handle))) {
            if (!in_array($file, $nomask) && $file[0] != '.') {
               if (is_dir("$dir/$file")) {
                  // skip "sites" folder, its subdirectories, and its files
                  if ($file != "sites"){
                     // Recurse into subdirectories
                     file_fix_directory("$dir/$file", $nomask);
               else {
                  if ($dir != dirname(__FILE__)){
                     $filename = "$dir/$file";
                     // Try to make each file 0555
                     if (@chmod($filename, 0555)) {
                        echo "<p>Made 0555: " . $filename . "</p>";
         } // while

   } // function

Add new comment