set permissions for all files and folders recursively

set permissions for all files and folders recursively

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Recursive Permission Management: Fixing Flawed Logic and Choosing the Right Tool

When managing file systems, specifically setting permissions recursively, you often encounter snippets of code that look functional at a glance but harbor subtle logical errors. A common request is to set directories to 750 and files to 644. While the goal is straightforward, implementing this logic in PHP using legacy functions like opendir() and readdir() can lead to unexpected behavior if not carefully structured.

Consider a function attempting to traverse a directory tree:

function chmod_r($Path) {
   $dp = opendir($Path);
   while($File = readdir($dp)) {
      if($File != "." AND $File != "..") {
         if(is_dir($File)){
            chmod($File, 0750);
         }else{
             chmod($Path."/".$File", 0644); // Syntax error in source
             if(is_dir($Path."/".$File)) { 
                // Logic contradiction: previous else block implies it wasn't a dir
                chmod_r($Path."/".$File); 
             }
         }
      }
   }
   closedir($dp);
}

This specific implementation contains critical flaws that would prevent it from working as intended. First, there is a logical contradiction in the control flow. The else block executes only if $File is not a directory (based on the is_dir check immediately preceding the function call). However, the code inside the else block attempts to check is_dir($Path."/".$File) again and recursively call itself. This creates a scenario where the code tries to recurse into a path it has just determined should be treated as a file, or conversely, misses the recursive step entirely because of the misplaced logic gates.

Furthermore, using opendir() with the deprecated readdir() loop is inefficient for deep directory structures and can hang if a directory contains a circular symlink or an infinite stream of files in older PHP versions. The function also fails to handle symlinks explicitly, potentially applying permissions to the target rather than the link itself depending on how is_dir resolves the path.

The Robust Shell Approach

For most production environments, relying on shell commands is often more robust and performant than writing custom recursive functions in PHP. The find utility combined with chmod provides a declarative way to handle permissions that is less prone to logic errors.

To set directories to 750 and files to 644 recursively, you can use the following command:

find /path/to/directory -type d -exec chmod 750 {} + \
    -execdir stat --format='%n %a' {} + | while read dir perms; do
        # Verify and adjust if necessary (optional safety check)
    done && \
find /path/to/directory -type f -exec chmod 644 {} +

A simpler, more direct approach often preferred by system administrators is:

find . -type d -exec chmod 750 {} +
find . -type f -exec chmod 644 {} +

The -exec ... + syntax batches the command execution, which is significantly faster than -exec ... \;, which invokes the command once per file. This batching is crucial when dealing with large datasets where performance matters.

Implementing in PHP Safely

If you must implement this logic within a PHP application, avoid the pitfalls of the example code provided earlier. Instead, utilize the RecursiveDirectoryIterator and FilesystemIterator. This approach leverages the SPL (Standard PHP Library) to handle recursion internally, reducing the risk of infinite loops or missed entries.

Here is a safer implementation pattern:

$iterator = new RecursiveDirectoryIterator('/path/to/directory');
$recursiveIterator = new RecursiveIteratorIterator($iterator);

foreach ($recursiveIterator as $file) {
    if ($file->isDir()) {
        chmod($file->getPathname(), 0750);
    } elseif ($file->isFile()) {
        // Ignore symlinks here if you want to modify the actual file, 
        // or check isLink() first depending on requirements.
        chmod($file->getPathname(), 0644);
    }
}

This method separates directory and file checks cleanly using isDir() and isFile(). It avoids string concatenation errors like $Path."/".$File which can lead to double slashes or incorrect path resolution. It also implicitly handles symlink traversal better than manual loops, provided you configure the iterator correctly if you need to skip them.

Trade-offs and Considerations

While shell commands offer speed and simplicity, they require elevated privileges (root or specific permissions) to execute effectively. If your application runs under a restricted user context, you cannot run find with root permissions unless you explicitly switch users or use sudo. In such cases, the PHP approach is necessary but must be implemented with care regarding performance on large directories.

Additionally, always consider the implications of symlinks. Setting permissions on a symlink usually affects the target file when accessed through that link, but the permission bits on the link entry itself are distinct. If your security model requires specific handling for symlinks (e.g., preventing traversal or setting specific ownership), you must add explicit checks before applying chmod.

In summary, avoid fragile recursive functions built on deprecated iterators. Prefer standard library tools like RecursiveDirectoryIterator in PHP or optimized shell commands via find to ensure consistent and secure permission management across your file system.

Our network