PHP script to fix permissions of all files and folders (and sub-folders) in a directory

There are times when we come across servers where the files are not given correct permissions. Changing file permission by accessing individual files and folders is one option. However, this is not possible when you have 100’s of files and sub-folders assosciated with them. That is when this script is useful. We only need to run the script once in order to fix the permissions of all the files, folders and subfolders (and their files) in order to get this fixed.

Requirements:
– PHP installed and working
– domain name or temp url to run the script

Follow these steps to get the issue with file and folder permissions fixed:

  • Access your file manager –> folder where you want to place the script (usually public_html)
  • Create a new file and save it with the php extension. Say: permission.php
  • Select the file and click on edit
  • Copy paste the code below into the file and save it
  • Access the script through your website / temp url. In this case: http://your_domain.com/permission.php
  • All the Files and Folders should now have permission of 644 and 755 respectively.
<?php

file_fix_directory(dirname(__FILE__));

function file_fix_directory($dir, $nomask = array('.', '..')) {
  if (is_dir($dir)) {
     // Try to make each directory world writable.
     if (@chmod($dir, 0755)) {
       echo "<p>Made writable: " . $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")) {
          // Recurse into subdirectories
          file_fix_directory("$dir/$file", $nomask);
        }
        else {
          $filename = "$dir/$file";
            // Try to make each file world writable.
            if (@chmod($filename, 0644)) {
              echo "<p>Made writable: " . $filename . "</p>";
            }
        }
      }
    }

    closedir($handle);
  }

}
?> 

/ /

Report (Please include link to post while reporting)

Leave a Reply

Your email address will not be published. Required fields are marked *