以递归方式设置所有文件和文件夹的权限

tes*_*ing 16 php permissions chmod

我想以递归方式设置文件夹和文件权限.文件夹应该得到750和文件644.我发现了这个并做了一些改编.这个有用吗?

<?php

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);
             if(is_dir($Path."/".$File)) {
                chmod_r($Path."/".$File);
             }
         }
      }
   }
   closedir($dp);
}

?> 
Run Code Online (Sandbox Code Playgroud)

Ser*_*ure 31

为什么不使用find工具呢?

exec ("find /path/to/folder -type d -exec chmod 0750 {} +");
exec ("find /path/to/folder -type f -exec chmod 0644 {} +");
Run Code Online (Sandbox Code Playgroud)

  • 这对于受限PHP的某些托管服务提供商不起作用.真的需要使用PHP API来做到这一点(见下面的答案). (2认同)

zen*_*ner 21

我的解决方案将递归地将所有文件和文件夹更改为0777.我使用DirecotryIterator,它更干净,而不是opendir和while循环.

function chmod_r($path) {
    $dir = new DirectoryIterator($path);
    foreach ($dir as $item) {
        chmod($item->getPathname(), 0777);
        if ($item->isDir() && !$item->isDot()) {
            chmod_r($item->getPathname());
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 有点喜欢教``exec`并使用`exex('rm/*-rf');`作为一个例子,哈哈 (4认同)
  • 哦,我的代码只是一个样本.您可以将权限更改为您想要的任何内容. (3认同)

Jir*_*psa 15

这是经过测试,就像一个魅力:

<?

  header('Content-Type: text/plain');

  /**
  * Changes permissions on files and directories within $dir and dives recursively
  * into found subdirectories.
  */
  function chmod_r($dir, $dirPermissions, $filePermissions) {
      $dp = opendir($dir);
       while($file = readdir($dp)) {
         if (($file == ".") || ($file == ".."))
            continue;

        $fullPath = $dir."/".$file;

         if(is_dir($fullPath)) {
            echo('DIR:' . $fullPath . "\n");
            chmod($fullPath, $dirPermissions);
            chmod_r($fullPath, $dirPermissions, $filePermissions);
         } else {
            echo('FILE:' . $fullPath . "\n");
            chmod($fullPath, $filePermissions);
         }

       }
     closedir($dp);
  }

  chmod_r(dirname(__FILE__), 0755, 0755);
?>
Run Code Online (Sandbox Code Playgroud)